﻿<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
	<title xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory">Chapter 16. Runtime Reference</title>
	<link rel="stylesheet" href="css/espertech.css" type="text/css">
	<meta xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" name="generator" content="DocBook XSL-NS Stylesheets V1.74.0">
	<meta xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="home" href="index.html" title="Esper Reference">
	<link rel="up" href="index.html" title="Esper Reference">
	<link rel="prev" href="apicompiler.html" title="Chapter 15. Compiler Reference">
	<link rel="next" href="configuration.html" title="Chapter 17. Configuration">
</head>

<body>
	<p xmlns:d="http://docbook.org/ns/docbook" id="title"><a href="./index.html" class="site_href"><strong>www.espertech.com</strong></a><a href="http://www.espertech.com/esper/esper-documentation/" class="doc_href"><strong>Documentation</strong></a></p>
	<ul xmlns:d="http://docbook.org/ns/docbook" class="docnav">
		<li class="previous"><a accesskey="p" href="apicompiler.html"><strong>Prev</strong></a></li>
		<li class="next"><a accesskey="n" href="configuration.html"><strong>Next</strong></a></li>
	</ul>
	<div class="chapter" lang="en-US">
		<div class="titlepage">
			<div>
				<div>
					<h2 class="title"><a id="apiruntime"></a>Chapter 16. Runtime Reference</h2>
				</div>
			</div>
		</div>
		<div class="toc">
			<dl>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-intro">16.1. Introduction</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-provider">16.2. Obtaining a Runtime From EPRuntimeProvider</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-runtime">16.3. The EPRuntime Runtime Interface</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-deployment">16.4. Deploying and Undeploying Using EPDeploymentService</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-deployment-substitution">16.4.1. Substitution Parameters</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-deployment-rollout">16.4.2. Roll-Out of Multiple Compiled Modules</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-deployment-atomic">16.4.3. Atomic Deployment Management</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-statement">16.5. Obtaining Results Using EPStatement</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-results">16.5.1. Receiving Statement Results</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-subscriber">16.5.2. Setting a Subscriber Object</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-addlisteners">16.5.3. Adding Listeners</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-iterators">16.5.4. Using Iterators</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-event">16.5.5. Event and Event Type</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-typeinfo">16.5.6. Type Information</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-statement-annotation">16.5.7. Interrogating Annotations</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-eventservice">16.6. Processing Events and Time Using EPEventService</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-eventservice-eventsender">16.6.1. Event Sender</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-eventservice-unmatched">16.6.2. Receiving Unmatched Events</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-fireandforget">16.7. Execute Fire-and-Forget Queries Using EPFireAndForgetService</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-fireandforget-single">16.7.1. Fire-and-forget Query Single Execution</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-fireandforget-prepared">16.7.2. Fire-and-forget Query Prepared Unparameterized Execution</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-fireandforget-preparedparameterized">16.7.3. Fire-and-forget Query Prepared Parameterized Execution</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-fireandforget-fromisoptional">16.7.4. The From-Clause is Optional</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-fireandforget-fromcansql">16.7.5. The From-Clause can Access Relational Data via SQL</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-threading">16.8. Runtime Threading and Concurrency</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-threading-advanced">16.8.1. Advanced Threading</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-processingorder">16.8.2. Processing Order</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-time">16.9. Controlling Time-Keeping</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-time-timespan">16.9.1. Controlling Time Using Time Span Events</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-time-resolution">16.9.2. Time Resolution and Time Unit</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-time-internal">16.9.3. Internal Timer Based on JVM System Time</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-exception">16.10. Exception Handling</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-condition">16.11. Condition Handling</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-instrumentation">16.12. Runtime and Statement Metrics Reporting</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-instrumentation-runtimemetrics">16.12.1. Runtime Metrics</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-instrumentation-statementmetrics">16.12.2. Statement Metrics</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-monitoring">16.13. Monitoring and JMX</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-output-rendering">16.14. Event Rendering to XML and JSON</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-output-rendering-json">16.14.1. JSON Event Rendering Conventions and Options</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-output-rendering-xml">16.14.2. XML Event Rendering Conventions and Options</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-plugin">16.15. Plug-In Loader</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-contextpartitionselection">16.16. Context Partition Selection</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#api-contextpartitionselection-selectors">16.16.1. Selectors</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-contextpartitionadmin">16.17. Context Partition Administration</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#api-testing">16.18. Test and Assertion Support</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#api-testing-assertion">16.18.1. EPAssertionUtil Summary</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#api-testing-listener">16.18.2. SupportUpdateListener Summary</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#api-testing-usage">16.18.3. Usage Example</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-osgi">16.19. OSGi, Class Loader, Class-For-Name</a></span></dt>
				<dt><span class="sect1"><a href="apiruntime.html#devlifecycle-j2ee">16.20. When Deploying with J2EE</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#devlifecycle-j2ee-considerations">16.20.1. J2EE Deployment Considerations</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#devlifecycle-j2ee-servletcontextlistener">16.20.2. Servlet Context Listener</a></span></dt>
					</dl>
				</dd>
				<dt><span class="sect1"><a href="apiruntime.html#apiruntime-stages">16.21. Stages</a></span></dt>
				<dd>
					<dl>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-stages-overview">16.21.1. Overview</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-stages-api">16.21.2. Stage APIs</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-stage-examplesuspendresume">16.21.3. Stage Example: Suspending and Resuming a Statement</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-stage-otherconsiderations">16.21.4. Stage Other Considerations</a></span></dt>
						<dt><span class="sect2"><a href="apiruntime.html#apiruntime-stage-limitations">16.21.5. Stage Limitations</a></span></dt>
					</dl>
				</dd>
			</dl>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-intro"></a>16.1. Introduction</h2>
					</div>
				</div>
			</div>
			<p>
				The runtime takes on these functions:
			</p>
			<div class="itemizedlist">
				<ul>
					<li>
						<p>Provide an environment to execute compiled modules.</p>
					</li>
					<li>
						<p>Provide an environment to run compiled fire-and-forget queries.</p>
					</li>
					<li>
						<p>Process incoming events and time against deployed modules.</p>
					</li>
				</ul>
			</div>
			<p>
				Your application obtains a runtime from <code class="literal">EPRuntimeProvider</code>. You may pass an arbitrary string-type runtime URI that uniquely identifies the runtime instance.
			</p>
			<p>
				A runtime is an instance of <code class="literal">EPRuntime</code>. Use the runtime as follows:
			</p>
			<div class="itemizedlist">
				<ul>
					<li>
						<p>The runtime is a stateful service.</p>
					</li>
					<li>
						<p>You may obtain and use any number of runtime instances in parallel, each runtime instance uniquely identified by the runtime URI.</p>
					</li>
					<li>
						<p>You may share a runtime instance between threads.</p>
					</li>
					<li>
						<p>All runtime methods are thread-safe.</p>
					</li>
					<li>
						<p>Each runtime is completely independent of other runtimes.</p>
					</li>
				</ul>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-provider"></a>16.2. Obtaining a Runtime From <code class="literal">EPRuntimeProvider</code></h2>
					</div>
				</div>
			</div><a id="d0e42437" class="indexterm"></a>
			<p>
				The <code class="literal">EPRuntimeProvider</code> class provides static methods that return <code class="literal">EPRuntime</code> runtimes.
			</p>
			<p>
				Each runtime has a unique runtime URI which can be any string value.
				If your application does not pass a runtime URI then the default URI is <code class="literal">default</code> (as defined by <code class="literal">EPRuntimeProvider.DEFAULT_RUNTIME_URI</code>).
			</p>
			<p>
				For the <code class="literal">getRuntime</code> methods, your application can pass a runtime URI to obtain different runtimes. The <code class="literal">EPRuntimeProvider</code>
				determines whether the provided runtime URI matches any existing runtime URIs and returns the existing runtime, or allocates a new runtime if none was found.
			</p>
			<p>
				The <code class="literal">getExistingRuntime</code> method takes a runtime URI and returns the existing runtime for that URI or <code class="literal">null</code> if there is none.
			</p>
			<p>
				The code snip below gets the default runtime. Subsequent calls to get the default runtime return the same runtime.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();</pre>
			<p>
				The next code gets a runtime for the runtime URI <code class="literal">RFIDProcessor1</code>. Subsequent calls to get a runtime with the same runtime URI return the same runtime instance.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPRuntime runtime = EPRuntimeProvider.getRuntime("RFIDProcessor1");</pre>
			<p>
				Since the <code class="literal">getRuntime</code> methods return the same runtime for each URI there is no need to statically cache a runtime in your application.
			</p>
			<p>
				You may also pass an optional <code class="literal">Configuration</code>.
				The next code snippet outlines a typical sequence of use:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Configure the runtime, this is optional
Configuration config = new Configuration();
config.configure("configuration.xml");	// load a configuration from file

// Optionally set additional configuration values like so:
// config.getCommon().add....(...);

// Obtain a runtime
EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime(config);

// Optionally, use initialize if the same runtime has been used before to start clean
runtime.initialize();

// Destroy the runtime when no longer needed, frees up resources, releases the runtime URI
runtime.destroy();</pre>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-runtime"></a>16.3. The <code class="literal">EPRuntime</code> Runtime Interface</h2>
					</div>
				</div>
			</div><a id="d0e42501" class="indexterm"></a>
			<p>
				The <code class="literal">EPRuntime</code> interface represents a runtime. Only the static methods of the <code class="literal">EPRuntimeProvider</code> class allocate new runtimes.
				A runtime is uniquely identified by runtime URI. The runtime URI is an arbitrary string. The default runtime has a runtime URI of <code class="literal">default</code>.
			</p>
			<p>
				A runtime provides these services:
			</p>
			<div class="table"><a id="apiruntime-runtime-services"></a>
				<p class="title"><b>Table 16.1. Choices For Receiving Statement Results</b></p>
				<div class="table-contents">
					<table summary="Choices For Receiving Statement Results" border="1">
						<colgroup>
							<col>
							<col>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>Service</th>
								<th>Runtime Method</th>
								<th>Description</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td><code class="literal">EPDeploymentService</code></td>
								<td><code class="literal">getDeploymentService</code></td>
								<td>
									<p>For deploying and undeploying compiled modules.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPEventService</code></td>
								<td><code class="literal">getEventService</code></td>
								<td>
									<p>For processing events and advancing time.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPContextPartitionService</code></td>
								<td><code class="literal">getContextPartitionService</code></td>
								<td>
									<p>For information about context partitions.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPVariableService</code></td>
								<td><code class="literal">getVariableService</code></td>
								<td>
									<p>For access to variables.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPEventTypeService</code></td>
								<td><code class="literal">getEventTypeService</code></td>
								<td>
									<p>For obtaining event types.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPFireAndForgetService</code></td>
								<td><code class="literal">getFireAndForgetService</code></td>
								<td>
									<p>For executing fire-and-forget queries.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPDataFlowService</code></td>
								<td><code class="literal">getDataFlowService</code></td>
								<td>
									<p>For managing data flows.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPMetricsService</code></td>
								<td><code class="literal">getMetricsService</code></td>
								<td>
									<p>For control over metrics, and for reading current metrics.</p>
								</td>
							</tr>
							<tr>
								<td><code class="literal">EPRenderEventService</code></td>
								<td><code class="literal">getRenderEventService</code></td>
								<td>
									<p>For rendering events.</p>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div><br class="table-break">
			<p>
				You can reset a runtime by calling the <code class="literal">initialize</code> method. This operation resets the runtime to the configuration last provided to <code class="literal">EPRuntimeProvider</code>. If no configuration is provided, an empty (default) configuration applies.
				Your application must obtain new services from the initialized runtime as initialize marks existing services as invalid.
			</p>
			<p>
				A runtime can be destroyed via the <code class="literal">destroy</code> method. This frees all resources held by the runtime. After a call to <code class="literal">destroy</code> the runtime can no longer be used.
			</p>
			<p>
				You may register callbacks to receive notifications about runtime state. The runtime invokes any <code class="literal">EPRuntimeStateListener</code> callbacks when a runtime instance is about to be destroyed and after a runtime has been initialized.
				Use the <code class="literal">addRuntimeStateListener</code> methods to register interest.
			</p>
			<p>
				When destroying a runtime your application must make sure that threads that are sending events into the runtime have completed their work. More generally, the runtime should not be currently in use during or after the destroy operation.
			</p>
			<p>
				All runtime instances are completely independent. Your application may not send <code class="literal">EventBean</code> instances obtained from one runtime into a second runtime since the event type space between two runtimes is not shared.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-deployment"></a>16.4. Deploying and Undeploying Using <code class="literal">EPDeploymentService</code></h2>
					</div>
				</div>
			</div><a id="d0e42659" class="indexterm"></a><a id="d0e42662" class="indexterm"></a>
			<p>
				Your application must first compile a module or obtain a compiled module before it can deploy. The object representation of a compiled module is <code class="literal">EPCompiled</code>.
			</p>
			<p>
				Call the <code class="literal">deploy</code> method and pass the compiled module. The runtime loads the byte code and adds the information contained in the byte code, causing all the compiled module's statements to begin receiving events and time.
			</p>
			<p>
				Deploying is an atomic operation. At deployment completion all statements of the deployment begin to see events arriving and time passing consistently.
				In case the deployment fails the runtime rolls back all deployment changes.
			</p>
			<p>
				The runtime resolves dependencies of the compiled module upon its deployment. The runtime does not validate that the information about EPL-object dependencies that existed at compile-time matches the runtime EPL-objects.
			</p>
			<p>
				For example, assume there is a compiled module by name <code class="literal">compiledModuleM1</code>. Deploy as follows:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPDeployment deployment = runtime.getDeploymentService().deploy(compiledModuleM1);</pre>
			<p>
				The runtime returns a <code class="literal">EPDeployment</code> instance that contains the deployment id, the <code class="literal">EPStatement</code> statement instances, module name and module properties.
				The deployment id is an arbitrary string-type identifier that uniquely identifies the deployment in the runtime.
			</p>
			<p>
				The <code class="literal">undeploy</code> method takes the deployment id and undeploys the deployment. The <code class="literal">undeployAll</code> method undeploys all deployments.
			</p>
			<p>
				A compiled module may be deployed any number of times. Substitution parameters can be handy for parameterizing deployed modules.
			</p>
			<p>
				Your application may deploy and undeploy using any thread and also within listener or subscriber code. If using Bean-style class-based events your application may not invoke deploy or undeploy methods as part of getter or setter code.
				Extension API code and plug-in single-row methods also may not invoke deploy or undeploy methods.
			</p>
			<p>
				You may pass a <code class="literal">DeploymentOptions</code> instance. Deployment options provide deployment callbacks and other deploy-time parameters:
			</p>
			<div class="itemizedlist">
				<ul>
					<li>
						<p>Provide a deployment id. If none is provided the runtime generates a unique deployment id.</p>
					</li>
					<li>
						<p>Provide substitution parameter values for parameterized modules.</p>
					</li>
					<li>
						<p>Provide or override statement names.</p>
					</li>
					<li>
						<p>Provide a runtime statement user object that gets associated to the statement and that can be obtained from an <code class="literal">EPStatement</code> with <code class="literal">getUserObjectRuntime</code>.</p>
					</li>
				</ul>
			</div>
			<p>
				Please consult the JavaDoc for more information.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-deployment-substitution"></a>16.4.1. Substitution Parameters</h3>
						</div>
					</div>
				</div>
				<p>
					The compiled module may have substitution parameters as explained in the compiler documentation.
				</p>
				<p>
					All substitution parameters must be replaced by actual values before a compiled module with substitution parameters can be deployed.
					A compiled module may be deployed multiple times. Substitution parameters can be set to new values for every deployment.
				</p>
				<p>
					To set substitution parameter values pass a <code class="literal">Deployment Options</code> object to the <code class="literal">deploy</code> method that provides a <code class="literal">StatementSubstitutionParameterOption</code>.
				</p>
				<p>
					If not assigning a name to substitution parameters, replace the substitution parameter with an actual value using the <code class="literal">setObject(int index, Object value)</code> method for each index, starting from 1.
				</p>
				<p>
					If assigning a name to each substitution parameter, replace the substitution parameter with an actual value using the <code class="literal">setObject(String name, Object value)</code> method for each name.
				</p>
				<p>
					While the <code class="literal">setObject</code> method allows substitution parameters to assume any actual value including application Java objects or enumeration values, the application must provide the correct type of substitution parameter that matches the requirements of the expression the parameter resides in.
				</p>
				<p>
					The below sample code compiles and deploys a parameterized module:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String stmt = "select * from PersonEvent(firstName=?::string)";
Configuration configuration = new Configuration();
configuration.getCommon().addEventType(PersonEvent.class);
CompilerArguments compilerArguments = new CompilerArguments(configuration);
EPCompiled compiled = EPCompilerProvider.getCompiler().compile(stmt, compilerArguments);

DeploymentOptions deploymentOptions = new DeploymentOptions();
deploymentOptions.setStatementSubstitutionParameter(prepared -&gt; prepared.setObject(1, "Joe")); 
EPDeployment deployment = runtime.getDeploymentService().deploy(compiled, deploymentOptions);
EPStatement statement = deployment.getStatements()[0];</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-deployment-rollout"></a>16.4.2. Roll-Out of Multiple Compiled Modules</h3>
						</div>
					</div>
				</div>
				<p>
					Your application may deploy multiple compiled modules by calling the <code class="literal">rollout</code> method of <code class="literal">EPDeploymentService</code>. Roll-out deploys each compiled module, either deploying all compiled modules or deploying none of the compiled modules.
				</p>
				<p>
					Internally to the runtime, a roll-out generally follows these steps:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>For each compiled module, determine the deployment id or use the deployment id when provided in the deployment options; Check that all deployment ids do not already exist</p>
						</li>
						<li>
							<p>For each compiled module, load the compilation unit via classloader and validate basic class-related information such as manifest information and version</p>
						</li>
						<li>
							<p>For each compiled module, check deployment preconditions and resolve deployment dependencies on EPL objects</p>
						</li>
						<li>
							<p>For each compiled module, initialize statement-internal objects</p>
						</li>
						<li>
							<p>For each compiled module, perform internal deployment of each statement of each module</p>
						</li>
					</ol>
				</div>
				<p>
					In case any of the above steps fail the runtime completely rolls back all changes.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						Roll-out does not re-order compiled modules and expects <code class="literal">EPCompiled</code> instances to be ordered according to module dependencies (if any).
					</p>
					<p>
						For multiple rollouts or for atomically adding listeners and subscribers use <a class="xref" href="apiruntime.html#apiruntime-deployment-atomic" title="16.4.3. Atomic Deployment Management">Section 16.4.3, “Atomic Deployment Management”</a>.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-deployment-atomic"></a>16.4.3. Atomic Deployment Management</h3>
						</div>
					</div>
				</div>
				<p>
					Your application can concurrently send events into the runtime while deploying and undeploying statements and adding or removing listeners. It is safe to undeploy and deploy compiled modules
					while sending in events from other threads concurrently.
				</p>
				<p>
					However in some cases your application may need more control over deployment, for example when deploying multiple modules or when attaching custom listener code.
				</p>
				<p>
					Your application can use the API described below to obtain a lock and perform deployment actions as an atomic unit.
					For example, if your application would like to undeploy and re-deploy as a single atomic unit, while at the same time sending events into the runtime from different threads,
					it can obtain a lock to ensure that no events are concurrently processed while the operations take place.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						Deploying or undeploying a single compiled module is already an atomic operation by default and does not require taking an explicit lock.
						If your application would like to deploy multiple compiled modules or add custom listeners or subscribers during deployment it may obtain a lock as discussed below.
					</p>
				</div>
				<p>
					The below code sample obtains the runtime exclusive write lock to perform multiple management operations as a unit, excluding concurrent processing of events.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">runtime.getRuntimeInstanceWideLock().writeLock().lock();
// Start atomic management unit. 
// Any events concurrently being processed by other threads must complete before the code completes obtaining the lock. 
// Any events sent in by other threads will await the release of the lock.
try {
  // Perform operations such as : 
  //   - deploy and/or undeploy multiple compiled modules  (deployment admin API)
  //   - set statement listeners and subscribers while deploying
  // There is no need to obtain this lock when deploying or undeploying a single module.
  // The lock is reentrant and can be safely taken multiple times by the same thread.
  // Make sure you use "try" and "finally" just like we have it here.
}
finally {
  // Complete atomic management unit. 
  // Any events sent in by other threads will now continue processing against the changed set of statements.
  runtime.getRuntimeInstanceWideLock().writeLock().unlock();
}</pre>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						There should always be a <code class="literal">finally</code> block in your code to ensure the lock is released in all cases.
					</p>
				</div>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-statement"></a>16.5. Obtaining Results Using <code class="literal">EPStatement</code></h2>
					</div>
				</div>
			</div>
			<p>
				A compiled module contains zero, one or multiple statements. You can attach callbacks (listeners, subscribers) to statements to receive results (aka push, observer pattern).
				You can iterate statement current results (aka. poll).
			</p>
			<p>
				Each statement is uniquely identified in the runtime by the combination of deployment id and statement name. The compiler or runtime always assign a statement name if none was provided.
			</p>
			<p>
				The <code class="literal">EPStatement</code> instance represents the statement. Your application receives statements when deploying a module by calling <code class="literal">getStatements</code> on <code class="literal">EPDeployment</code>.
			</p>
			<p>
				Your application may also look up a statement by it's deployment id and statement name using the <code class="literal">getStatement</code> method on <code class="literal">EPDeploymentService</code>.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-results"></a>16.5.1. Receiving Statement Results</h3>
						</div>
					</div>
				</div><a id="d0e42863" class="indexterm"></a>
				<p>
					For NEsper .NET also see <a class="xref" href="appendix_dotnet.html#appendix_dotnet_api_receive_results" title="J.15. .NET API - Receiving Statement Results">Section J.15, “.NET API - Receiving Statement Results”</a>.
				</p>
				<p>
					Esper provides three choices for your application to receive statement results. Your application can use all three mechanisms alone or in any combination for each statement. The choices are:
				</p>
				<div class="table"><a id="apiruntime-statement-receiveresults"></a>
					<p class="title"><b>Table 16.2. Choices For Receiving Statement Results</b></p>
					<div class="table-contents">
						<table summary="Choices For Receiving Statement Results" border="1">
							<colgroup>
								<col>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Name</th>
									<th>Methods on <code class="literal">EPStatement</code></th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Listener Callbacks</td>
									<td><code class="literal">addListener</code> and <code class="literal">removeListener</code></td>
									<td>
										<p>
											Your application provides implementations of the <code class="literal">UpdateListener</code> interface to the statement.
											Listeners receive <code class="literal">EventBean</code> instances containing statement results.
										</p>
										<p>The runtime continuously indicates results to all listeners.</p>
									</td>
								</tr>
								<tr>
									<td>Subscriber Object</td>
									<td><code class="literal">setSubscriber</code></td>
									<td>
										<p>
											Requires setting the <code class="literal">allowSubscriber</code> option on the compiler.
										</p>
										<p>
											Your application provides a POJO (plain Java object) that exposes methods to receive statement results.
										</p>
										<p>
											The name of the method that a subscriber object provides to receive results is <code class="literal">update</code>, unless your call to <code class="literal">setSubscriber</code> provides
											another method name.
										</p>
										<p>The runtime continuously indicates results to the single subscriber.</p>
										<p>
											This is the fastest method to receive statement results, as the runtime delivers strongly-typed results directly to your application objects without the need for
											building an <code class="literal">EventBean</code> result set.
										</p>
										<p>
											There can be at most one subscriber object registered per statement. If you require more than one listener, use the listener instead (or in addition).
											The subscriber object is bound to the statement with a strongly typed support which ensure direct delivery of new events without type conversion. This optimization
											is made possible because there can only be zero or one subscriber object per statement.
										</p>
									</td>
								</tr>
								<tr>
									<td>Pull API</td>
									<td><code class="literal">safeIterator</code> and <code class="literal">iterator</code></td>
									<td>
										<p>Your application asks the statement for results and receives a set of events via <code class="literal">java.util.Iterator&lt;EventBean&gt;</code>.</p>
										<p>This is useful if your application does not need continuous indication of new results in real-time.</p>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
					<h2>Tip</h2>
					<p>
						The runtime calls application-provided update listeners and subscribers for output. These commonly encapsulate the actions to take when there is output.
						This design decouples statements from actions and places actions outside of EPL. It allows actions to change independently from statements: A statement
						does not need to be updated when its associated action(s) change.
					</p>
					<p>
						While action-taking, in respect to the code or script taking action, is not a part of the EPL language, here are a few noteworthy points.
						Through the use of EPL annotations you can attach information to EPL that can be used by applications to flexibly determine actions.
						The <code class="literal">insert into</code>-clause can be used to send results into a further stream and input and output adapters or data flows can exist to process output events from that stream.
						Also the data flow <code class="literal">EPStatementSource</code> operator can be used to hook up actions declaratively.
						The <code class="literal">DeploymentStateListener</code> can inform your application of newly-deployed statements and currently-undeployed statements.
					</p>
				</div>
				<p>
					Your application may attach one or more listeners, zero or one single subscriber and in addition use the pull API on the same statement. There are no limitations to the use of iterator, subscriber or listener
					alone or in combination to receive statement results.
				</p>
				<p>
					The best delivery performance can generally be achieved by attaching a subscriber and by not attaching listeners.
					The runtime is aware of the listeners and subscriber attached to a statement. The runtime uses this information internally to reduce statement overhead. For example, if your statement does not have listeners or a subscriber attached, the runtime does not need to continuously generate results for delivery.
				</p>
				<p>
					If your application attaches both a subscriber and one or more listeners then the subscriber receives the result first before any of the listeners.
				</p>
				<p>
					If your application attaches more than one listener then the <code class="literal">UpdateListener</code> listeners receive results in the order they were added to the statement.
					To change the order of delivery among listeners your application can add and remove listeners at runtime.
				</p>
				<p>
					If you have configured outbound threading, it means a thread from the outbound thread pool delivers results to the subscriber and listeners instead of the processing or event-sending thread.
				</p>
				<p>
					If outbound threading is turned on, we recommend turning off the runtime setting preserving the order of events delivered to listeners as described in <a class="xref" href="configuration.html#configuration-runtime-threading-dispatch" title="17.6.1.1. Preserving the Order of Events Delivered to Listeners">Section 17.6.1.1, “Preserving the Order of Events Delivered to Listeners”</a>. If outbound threading is turned on statement execution is not blocked for the configured time in the case a subscriber or listener takes too much time.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-subscriber"></a>16.5.2. Setting a Subscriber Object</h3>
						</div>
					</div>
				</div><a id="d0e43007" class="indexterm"></a><a id="d0e43010" class="indexterm"></a>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>The compiler option <code class="literal">allowSubscriber</code> must be set at compile-time.</p>
				</div>
				<p>
					A subscriber object is a direct binding of statement results to an object. The object, receives statement results via method invocation. The subscriber class does not need to implement an interface or extend a superclass. Only one subscriber object may be set for a statement.
				</p>
				<p>
					Subscriber objects have several advantages over listeners. First, they offer a substantial performance benefit: Statement results are delivered directly to your method(s) through Java virtual machine method calls, and there is no intermediate representation (<code class="literal">EventBean</code>). Second, as subscribers receive strongly-typed parameters, the subscriber code tends to be simpler.
				</p>
				<p>
					This chapter describes the requirements towards the methods provided by your subscriber class.
				</p>
				<p>
					The runtime can deliver results to your subscriber in two ways:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								Each evert in the insert stream results in a method invocation, and each event in the remove stream results in further method invocations. This is termed <span class="emphasis"><em>row-by-row delivery</em></span>.
							</p>
						</li>
						<li>
							<p>
								A single method invocation that delivers all rows of the insert and remove stream. This is termed <span class="emphasis"><em>multi-row</em></span> delivery.
							</p>
						</li>
					</ol>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="api-admin-subscriber-epstatement"></a>16.5.2.1. Using the <code class="literal">EPStatement</code> Parameter</h4>
							</div>
						</div>
					</div><a id="d0e43051" class="indexterm"></a>
					<p>
						In the case that your subscriber object wishes to receive the <code class="literal">EPStatement</code> instance along with output data,
						please add <code class="literal">EPStatement</code> as the very first parameter of any of the delivery method footprints that are discussed next.
					</p>
					<p>
						For example, your statement may be:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select count(*) from OrderEvent</pre>
					<p>
						Your subscriber class exposes the method:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(EPStatement statement, long currentCount) {...}</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="api-admin-subscriber-rowbyrow"></a>16.5.2.2. Row-by-Row Delivery</h4>
							</div>
						</div>
					</div><a id="d0e43075" class="indexterm"></a>
					<p>
						Your subscriber class must provide a method by name <code class="literal">update</code> to receive insert stream events row-by-row. The number and types of parameters declared by the <code class="literal">update</code> method must match the number and types of columns as specified in the <code class="literal">select</code> clause, in the same order as in the <code class="literal">select</code> clause.
					</p>
					<p>
						For example, if your statement is:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select orderId, price, count(*) from OrderEvent</pre>
					<p>
						Then your subscriber <code class="literal">update</code> method looks as follows:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class MySubscriber {
  ...
  public void update(String orderId, double price, long count) {...}
  ...
}</pre>
					<p>
						Each method parameter declared by the <code class="literal">update</code> method must be assignable from the respective column type as listed in the <code class="literal">select</code>-clause, in the order selected. The assignability rules are:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									Widening of types follows Java standards. For example, if your <code class="literal">select</code> clause selects an integer value, the method parameter for the same column can be typed int, long, float or double (or any equivalent boxed type).
								</p>
							</li>
							<li>
								<p>
									Auto-boxing and unboxing follows Java standards. For example, if your <code class="literal">select</code> clause selects an <code class="literal">java.lang.Integer</code> value, the method parameter for the same column can be typed <code class="literal">int</code>. Note that if your <code class="literal">select</code> clause column may generate <code class="literal">null</code> values, an exception may occur at runtime unboxing the <code class="literal">null</code> value.
								</p>
							</li>
							<li>
								<p>
									Interfaces and super-classes are honored in the test for assignability. Therefore <code class="literal">java.lang.Object</code> can be used to accept any <code class="literal">select</code> clause column type
								</p>
							</li>
						</ul>
					</div>
					<p>
						In the case that your subscriber class offers multiple <code class="literal">update</code> method footprints, the runtime selects the closest-matching footprint by comparing the output types and method parameter types. The runtime prefers the update method that is an exact match of types, followed by an update method that requires boxing or unboxing, followed by an update method that requires widening and finally any other allowable update method.
					</p>
					<p>
						Within the above criteria, in the case that your subscriber class offers multiple <code class="literal">update</code> method footprints with same method parameter types, the runtime prefers the update method that has <code class="literal">EPStatement</code> as the first parameter.
					</p>
					<div class="sect4" lang="en-US">
						<div class="titlepage">
							<div>
								<div>
									<h5 class="title"><a id="api-admin-subscriber-rowbyrow-wildcard"></a>16.5.2.2.1. Wildcards</h5>
								</div>
							</div>
						</div>
						<p>
							If your <code class="literal">select</code> clause contains one or more wildcards (*), then the equivalent parameter type is the underlying event type of the stream selected from.
						</p>
						<p>
							For example, your statement may be:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select *, count(*) from OrderEvent</pre>
						<p>
							Then your subscriber <code class="literal">update</code> method looks as follows:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(OrderEvent orderEvent, long count) {...}</pre>
						<p>
							In a join, the wildcard expands to the underlying event type of each stream in the join in the order the streams occur in the <code class="literal">from</code> clause. An example statement for a join is:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select *, count(*) from OrderEvent order, OrderHistory hist</pre>
						<p>
							Then your subscriber <code class="literal">update</code> method should be:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(OrderEvent orderEvent, OrderHistory orderHistory, long count) {...}</pre>
						<p>
							The stream wildcard syntax and the stream name itself can also be used:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select hist.*, order from OrderEvent order, OrderHistory hist</pre>
						<p>
							The matching <code class="literal">update</code> method is:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(OrderHistory orderHistory, OrderEvent orderEvent) {...}</pre>
					</div>
					<div class="sect4" lang="en-US">
						<div class="titlepage">
							<div>
								<div>
									<h5 class="title"><a id="api-admin-subscriber-rowbyrow-generic"></a>16.5.2.2.2. Row Delivery as Map and Object Array </h5>
								</div>
							</div>
						</div>
						<p>
							Alternatively, your <code class="literal">update</code> method may simply choose to accept <code class="literal">java.util.Map</code> as a representation for each row. Each column in the <code class="literal">select</code> clause is
							then made an entry in the resulting <code class="literal">Map</code>. The <code class="literal">Map</code> keys are the column name if supplied, or the expression string itself for columns without a name.
						</p>
						<p>
							The <code class="literal">update</code> method for <code class="literal">Map</code> delivery is:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(Map row) {...}</pre>
						<p>
							The runtime also supports delivery of <code class="literal">select</code> clause columns as an object array. Each item in the object array represents a column in the <code class="literal">select</code> clause. The <code class="literal">update</code> method then looks as follows:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(Object[] row) {...}</pre>
					</div>
					<div class="sect4" lang="en-US">
						<div class="titlepage">
							<div>
								<div>
									<h5 class="title"><a id="api-admin-subscriber-rowbyrow-rstream"></a>16.5.2.2.3. Delivery of Remove Stream Events</h5>
								</div>
							</div>
						</div>
						<p>
							Your subscriber receives remove stream events if it provides a method named <code class="literal">updateRStream</code>. The method must accept the same number and types of parameters as the <code class="literal">update</code> method (including <code class="literal">EPStatement</code> if present).
						</p>
						<p>
							An example statement:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select orderId, count(*) from OrderEvent#time(20 sec) group by orderId</pre>
						<p>
							Then your subscriber <code class="literal">update</code> and <code class="literal">updateRStream</code> methods should be:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(String, long count) {...}
public void updateRStream(String orderId, long count) {...}</pre>
					</div>
					<div class="sect4" lang="en-US">
						<div class="titlepage">
							<div>
								<div>
									<h5 class="title"><a id="api-admin-subscriber-rowbyrow-beginend"></a>16.5.2.2.4. Delivery of Begin and End Indications</h5>
								</div>
							</div>
						</div>
						<p>
							If your subscriber requires a notification for begin and end of event delivery, it can expose methods by name <code class="literal">updateStart</code> and <code class="literal">updateEnd</code>.
						</p>
						<p>
							The <code class="literal">updateStart</code> method must take two integer parameters that indicate the number of events of the insert stream and remove stream to be delivered. The runtime invokes the <code class="literal">updateStart</code> method immediately prior to delivering events to the <code class="literal">update</code> and <code class="literal">updateRStream</code> methods.
						</p>
						<p>
							The <code class="literal">updateEnd</code> method must take no parameters. The runtime invokes the <code class="literal">updateEnd</code> method immediately after delivering events to the <code class="literal">update</code> and <code class="literal">updateRStream</code> methods.
						</p>
						<p>
							An example set of delivery methods:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Called by the runtime before delivering events to update methods
public void updateStart(int insertStreamLength, int removeStreamLength)

// To deliver insert stream events
public void update(String orderId, long count) {...}

// To deliver remove stream events
public void updateRStream(String orderId, long count) {...}

// Called by the runtime after delivering events
public void updateEnd() {...}</pre>
					</div>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="api-admin-subscriber-multirow"></a>16.5.2.3. Multi-Row Delivery</h4>
							</div>
						</div>
					</div><a id="d0e43324" class="indexterm"></a>
					<p>
						In place of row-by-row delivery, your subscriber can receive all events in the insert and remove stream via a single method invocation. This is applicable when an EPL delivers multiple output rows for a given input event or time advancing, for example when multiple pattern matches occur for the same incoming event, for a join producing multiple output rows or with output rate limiting, for example.
					</p>
					<p>
						The event delivery follow the scheme as described earlier in <a class="xref" href="apiruntime.html#api-admin-subscriber-rowbyrow-generic" title="16.5.2.2.2. Row Delivery as Map and Object Array">Section 16.5.2.2.2, “Row Delivery as Map and Object Array ”</a>. The subscriber class must provide one of the following methods:
					</p>
					<div class="table"><a id="api-admin-subscriber-multirow-underlying"></a>
						<p class="title"><b>Table 16.3. Update Method for Multi-Row Delivery of Underlying Events</b></p>
						<div class="table-contents">
							<table summary="Update Method for Multi-Row Delivery of Underlying Events" border="1">
								<colgroup>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Method</th>
										<th>Description</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td><code class="literal">update(Object[][] insertStream, Object[][] removeStream)</code></td>
										<td>
											<p>The first dimension of each Object array is the event row, and the second dimension is the column matching the column order of the statement <code class="literal">select</code> clause</p>
										</td>
									</tr>
									<tr>
										<td><code class="literal">update(Map[] insertStream, Map[] removeStream)</code></td>
										<td>
											<p> Each map represents one event, and Map entries represent columns of the statement <code class="literal">select</code> clause</p>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<div class="sect4" lang="en-US">
						<div class="titlepage">
							<div>
								<div>
									<h5 class="title"><a id="api-admin-subscriber-multirow-wildcard"></a>16.5.2.3.1. Wildcards</h5>
								</div>
							</div>
						</div>
						<p>
							If your <code class="literal">select</code> clause contains a single wildcard (*) or wildcard stream selector, the subscriber object may also directly receive arrays of the underlying events. In this case, the subscriber class should provide a method <code class="literal">update(</code><span class="emphasis"><em>Underlying</em></span><code class="literal">[] insertStream, </code><span class="emphasis"><em>Underlying</em></span>[] <span class="emphasis"><em>removeStream</em></span><code class="literal">)</code> , such that <span class="emphasis"><em>Underlying</em></span> represents the class of the underlying event.
						</p>
						<p>
							For example, your statement may be:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from OrderEvent#time(30 sec)</pre>
						<p>
							Your subscriber class exposes the method:
						</p>
						<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update(OrderEvent[] insertStream, OrderEvent[] removeStream) {...}</pre>
					</div>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="api-admin-subscriber-null"></a>16.5.2.4. No-Parameter Update Method</h4>
							</div>
						</div>
					</div><a id="d0e43408" class="indexterm"></a>
					<p>
						In the case that your subscriber object wishes to receive no data from a statement please follow the instructions here.
					</p>
					<p>
						You statement must select a single <code class="literal">null</code> value.
					</p>
					<p>
						For example, your statement may be:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select null from OrderEvent(price &gt; 100)</pre>
					<p>
						Your subscriber class exposes the method:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void update() {...}</pre>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-addlisteners"></a>16.5.3. Adding Listeners</h3>
						</div>
					</div>
				</div><a id="d0e43431" class="indexterm"></a>
				<p>
					For NEsper .NET also see <a class="xref" href="appendix_dotnet.html#appendix_dotnet_api_admin_listeners" title="J.16. .NET API - Adding Listeners">Section J.16, “.NET API - Adding Listeners”</a>.
				</p>
				<p>
					Your application can subscribe to updates posted by a statement via the <code class="literal">addListener</code> and <code class="literal">removeListener</code> methods on <code class="literal">EPStatement</code> . Your application must to provide an implementation of the <code class="literal">UpdateListener</code> interface to the statement:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">UpdateListener myListener = new MyUpdateListener();
countStmt.addListener(myListener);</pre>
				<p>
					Statements publish old data and new data to registered <code class="literal">UpdateListener</code> listeners.
					New data published by statements is the events representing the new values of derived data held by the statement.
					Old data published by statements consists of the events representing the prior values of derived data held by the statement.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="important">
					<h2>Important</h2>
					<p>
						<code class="literal">UpdateListener</code> listeners receive multiple result rows in one invocation by the runtime: the new data and old data parameters to your listener are array parameters. For example, if your application uses one of the batch data windows, or your application creates a pattern that matches multiple times when a single event arrives, then the runtime indicates such multiple result rows in one invocation and your new data array carries two or more rows.
					</p>
				</div>
				<p>
					To indicate results the runtime invokes the following method on <code class="literal">UpdateListener</code> listeners: <code class="literal">update(EventBean[] newEvents, EventBean[] oldEvents, EPStatement statement, EPRuntime runtime)</code>
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-statement-listenersreplay"></a>16.5.3.1. Subscription Snapshot and Atomic Delivery</h4>
							</div>
						</div>
					</div>
					<p>
						The <code class="literal">addListenerWithReplay</code> method provided by <code class="literal">EPStatement</code> makes it possible to send a snapshot of current statement results to a listener when the listener is added.
					</p>
					<p>
						When using the <code class="literal">addListenerWithReplay</code> method to register a listener, the listener receives current statement results as the first call to the update method of the listener, passing in the newEvents parameter the current statement results as an array of zero or more events. Subsequent calls to the update method of the listener are statement results.
					</p>
					<p>
						Current statement results are the events returned by the <code class="literal">iterator</code> or <code class="literal">safeIterator</code> methods.
					</p>
					<p>
						Delivery is atomic: Events occurring during delivery of current results to the listener are guaranteed to be delivered in a separate call and not lost. The listener implementation should thus minimize long-running or blocking operations to reduce lock times held on statement-level resources.
					</p>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-iterators"></a>16.5.4. Using Iterators</h3>
						</div>
					</div>
				</div><a id="d0e43502" class="indexterm"></a><a id="d0e43505" class="indexterm"></a><a id="d0e43508" class="indexterm"></a>
				<p>
					Subscribing to events posted by a statement is following a push model. The runtime pushes data to listeners when events are received that cause data to change or patterns to match. Alternatively, you need to know that statements serve up data that your application can obtain via the <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods on <code class="literal">EPStatement</code>. This is called the pull API and can come in handy if your application is not interested in all new updates, and only needs to perform a frequent or infrequent poll for the latest data.
				</p>
				<p>
					The <code class="literal">safeIterator</code> method on <code class="literal">EPStatement</code> returns a concurrency-safe iterator returning current statement results, even while concurrent threads may send events into the runtime for processing. The runtime employs a read-write lock per context partition and obtains a read lock for iteration. Thus safe iterator guarantees correct results even as events are being processed by other threads and other context partitions. The cost is that the iterator obtains and holds zero, one or multiple context partition locks for that statement that must be released via the <code class="literal">close</code> method on the <code class="literal">SafeIterator</code> instance.
				</p>
				<p>
					The <code class="literal">iterator</code> method on <code class="literal">EPStatement</code> returns a concurrency-unsafe iterator. This iterator is only useful for applications that are single-threaded, or applications that themselves perform coordination between the iterating thread and the threads that send events into the runtime for processing. The advantage to this iterator is that it does not hold a lock.
				</p>
				<p>
					When statements are used with contexts and context partitions, the APIs to identify, filter and select context partitions for statement iteration are described in <a class="xref" href="apiruntime.html#apiruntime-contextpartitionselection" title="16.16. Context Partition Selection">Section 16.16, “Context Partition Selection”</a>.
				</p>
				<p>
					The next code snippet shows a short example of use of safe iterators:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPStatement statement = epAdmin.createEPL("select avg(price) as avgPrice from MyTick");
// .. send events into the runtime
// then use the pull API...
SafeIterator&lt;EventBean&gt; safeIter = statement.safeIterator();
try {
  for (;safeIter.hasNext();) {
     // .. process event ..
     EventBean event = safeIter.next();
     System.out.println("avg:" + event.get("avgPrice");
  }
}
finally {
  safeIter.close();	// Note: safe iterators must be closed
}</pre>
				<p>
					This is a short example of use of the regular iterator that is not safe for concurrent event processing:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">double averagePrice = (Double) eplStatement.iterator().next().get("average");</pre>
				<p>
					The <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods can be used to pull results out of all statements, including statements that join streams, contain aggregation functions, pattern statements, and statements that contain a <code class="literal">where</code> clause, <code class="literal">group by</code> clause, <code class="literal">having</code> clause or <code class="literal">order by</code> clause.
				</p>
				<p>
					For statements without an <code class="literal">order by</code> clause, the <code class="literal">iterator</code> method returns events in the order maintained by the data window. For statements that contain an <code class="literal">order by</code> clause, the <code class="literal">iterator</code> method returns events in the order indicated by the <code class="literal">order by</code> clause.
				</p>
				<p>
					Consider using the <code class="literal">on-select</code> clause and a named window if your application requires iterating over a partial result set or requires indexed access for fast iteration; Note that <code class="literal">on-select</code> requires that you sent a trigger event, which may contain the key values for indexed access.
				</p>
				<p>
					Esper places the following restrictions on the pull API and usage of the <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods:
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
					<ol>
						<li>
							<p>
								In multithreaded applications, use the <code class="literal">safeIterator</code> method. Note: make sure your application closes the iterator via the <code class="literal">close</code> method when done, otherwise the iterated statement context partitions stay locked and event processing for statement context partitions does not resume.
							</p>
						</li>
						<li>
							<p>
								In multithreaded applications, the <code class="literal">iterator</code> method does not hold any locks. The iterator returned by this method does not make any guarantees towards correctness of results and fail-behavior, if your application processes events into the runtime by multiple threads. Use the <code class="literal">safeIterator</code> method for concurrency-safe iteration instead.
							</p>
						</li>
						<li>
							<p>
								Since the <code class="literal">safeIterator</code> and <code class="literal">iterator</code> methods return events to the application immediately, the iterator does not honor an output rate limiting clause, if present. That is, the iterator returns results as if there is no output-rate clause for the statement in statements without grouping or aggregation. For statements with grouping or aggregation, the iterator in combination with an output clause returns last output group and aggregation results. Use a separate statement and the <code class="literal">insert into</code> clause to control the output rate for iteration, if so required.
							</p>
						</li>
						<li>
							<p>
								When iterating a statement that operates on an unbound stream (no data window declared), please note the following:
							</p>
							<div class="itemizedlist">
								<ul compact="compact">
									<li>
										<p>
											When iterating a statement that groups and aggregates values from an unbound stream and that specifies <code class="literal">output snapshot</code>, the runtime retains groups and aggregations for output as iteration results or upon the output snapshot condition .
										</p>
									</li>
									<li>
										<p>
											When iterating a statement that groups and aggregates values from an unbound stream and that does not specify <code class="literal">output snapshot</code>, the runtime only retains the last aggregation values and the iterated result contains only the last updated group.
										</p>
									</li>
									<li>
										<p>
											When iterating a statement that operates on an unbound stream the iterator returns no rows. This behavior can be changed by specifying either the <code class="literal">@IterableUnbound</code> annotation or by changing the global view resources configuration.
										</p>
									</li>
								</ul>
							</div>
						</li>
					</ol>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-event"></a>16.5.5. Event and Event Type</h3>
						</div>
					</div>
				</div><a id="d0e43665" class="indexterm"></a><a id="d0e43668" class="indexterm"></a>
				<p>
					An <code class="literal">EventBean</code> object represents a row (event) in your statement's result set. Each <code class="literal">EventBean</code> object has an associated <code class="literal">EventType</code> object providing event metadata.
				</p>
				<p>
					An <code class="literal">UpdateListener</code> implementation receives one or more <code class="literal">EventBean</code> events with each invocation. Via the <code class="literal">iterator</code> method on <code class="literal">EPStatement</code> your application can poll or read data out of statements. Statement iterators also return <code class="literal">EventBean</code> instances.
				</p>
				<p>
					Each statement provides the event type of the events it produces, available via the <code class="literal">getEventType</code> method on <code class="literal">EPStatement</code>.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-statement-eventtype"></a>16.5.5.1. Event Type Metadata</h4>
							</div>
						</div>
					</div>
					<p>
						An <code class="literal">EventType</code> object encapsulates all the metadata about a certain type of events. As Esper supports an inheritance hierarchy for event types, it also provides information about super-types to an event type.
					</p>
					<p>
						An <code class="literal">EventType</code> object provides the following information:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									For each event property, it lists the property name and type as well as flags for indexed or mapped properties and whether a property is a fragment.
								</p>
							</li>
							<li>
								<p>
									The direct and indirect super-types to the event type.
								</p>
							</li>
							<li>
								<p>
									Value getters for property expressions.
								</p>
							</li>
							<li>
								<p>
									Underlying class of the event representation.
								</p>
							</li>
						</ul>
					</div>
					<p>
						For each property of an event type, there is an <code class="literal">EventPropertyDescriptor</code> object that describes the property.
						The <code class="literal">EventPropertyDescriptor</code> contains flags that indicate whether a property is an indexed (array) or a mapped property and whether access to property values require an integer index value (indexed properties only) or string key value (mapped properties only). The descriptor also contains a fragment flag that indicates whether a property value is available as a fragment.
					</p>
					<p>
						The term <span class="emphasis"><em>fragment</em></span> means an event property value that is itself an event, or a property value that can be represented as an event. The <code class="literal">getFragmentType</code> on <code class="literal">EventType</code> may be used to determine a fragment's event type in advance.
					</p>
					<p>
						A fragment event type and thereby fragment events allow navigation over a statement's results even if the statement result contains nested events or a graph of events. There is no need to use the Java reflection API to navigate events,
						since fragments allow the querying of nested event properties or array values, including nested Java classes.
					</p>
					<p>
						When using the Map or Object-array event representation, any named Map type or Object-array type nested within a Map or Object-array as a simple or array property is also available as a fragment. When using Java objects either directly or within Map or Object-array events, any object that is neither a primitive or boxed built-in type, and that is not an enumeration and does not implement the Map interface is also available as a fragment.
					</p>
					<p>
						The nested, indexed and mapped property syntax can be combined to a property expression that may query an event property graph. Most of the methods on the <code class="literal">EventType</code> interface allow a property expression to be passed.
					</p>
					<p>
						Your application may use an <code class="literal">EventType</code> object to obtain special getter-objects. A getter-object is a fast accessor to a property value of an event of a given type. All getter objects implement the <code class="literal">EventPropertyGetter</code> interface. Getter-objects work only for events of the same type or sub-types as the <code class="literal">EventType</code> that provides the <code class="literal">EventPropertyGetter</code>. The performance section provides additional information and samples on using getter-objects.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-statement-eventbean"></a>16.5.5.2. Event Object</h4>
							</div>
						</div>
					</div>
					<p>
						An event object is an <code class="literal">EventBean</code> that provides:
					</p>
					<div class="itemizedlist">
						<ul compact="compact">
							<li>
								<p>
									The property value for a property given a property name or property expression that may include nested, indexed or mapped properties in any combination.
								</p>
							</li>
							<li>
								<p>
									The event type of the event.
								</p>
							</li>
							<li>
								<p>
									Access to the underlying event object.
								</p>
							</li>
							<li>
								<p>
									The <code class="literal">EventBean</code> fragment or array of <code class="literal">EventBean</code> fragments given a property name or property expression.
								</p>
							</li>
						</ul>
					</div>
					<p>
						The <code class="literal">getFragment</code> method on <code class="literal">EventBean</code> and <code class="literal">EventPropertyGetter</code> return the fragment <code class="literal">EventBean</code> or array of <code class="literal">EventBean</code>, if the property is itself an event
						or can be represented as an event. Your application may use <code class="literal">EventPropertyDescriptor</code> to determine which properties are also available as fragments.
					</p>
					<p>
						The underlying event object of an <code class="literal">EventBean</code> can be obtained via the <code class="literal">getUnderlying</code> method. Please see <a class="xref" href="event_representation.html" title="Chapter 3. Event Representations">Chapter 3, <i>Event Representations</i></a> for more information on different event representations.
					</p>
					<p>
						From a threading perspective, it is safe to retain and query <code class="literal">EventBean</code> and <code class="literal">EventType</code> objects in multiple threads.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-statement-eventtypequery"></a>16.5.5.3. Query Example</h4>
							</div>
						</div>
					</div>
					<p>
						Consider a statement that returns the symbol, count of events per symbol and average price per symbol for tick events. Our sample statement uses the event type: <code class="literal">StockTickEvent</code>. Assume that this event type was declared previously and exposes a <code class="literal">symbol</code> property of type String and a <code class="literal">price</code> property of type (Java primitive) double.
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select symbol, avg(price) as avgprice, count(*) as mycount 
from StockTickEvent 
group by symbol</pre>
					<p>
						The next table summarizes the property names and types as posted by the statement above:
					</p>
					<div class="table"><a id="d0e43858"></a>
						<p class="title"><b>Table 16.4. Properties Offered by Sample Statement Aggregating Price</b></p>
						<div class="table-contents">
							<table summary="Properties Offered by Sample Statement Aggregating Price" border="1">
								<colgroup>
									<col>
									<col>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Name</th>
										<th>Type</th>
										<th>Description</th>
										<th>Java code snippet</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td><code class="literal">symbol</code></td>
										<td>java.lang.String</td>
										<td>Value of symbol event property</td>
										<td>
											<pre class="synopsis">eventBean.get("symbol")</pre>
										</td>
									</tr>
									<tr>
										<td><code class="literal">avgprice</code></td>
										<td>java.lang.Double</td>
										<td>Average price per symbol</td>
										<td>
											<pre class="synopsis">eventBean.get("avgprice")</pre>
										</td>
									</tr>
									<tr>
										<td><code class="literal">mycount</code></td>
										<td>java.lang.Long</td>
										<td>Number of events per symbol</td>
										<td>
											<pre class="synopsis">eventBean.get("mycount")</pre>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						A code snippet out of a possible <code class="literal">UpdateListener</code> implementation to this statement may look as below:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String symbol = (String) newEvents[0].get("symbol");
Double price= (Double) newEvents[0].get("avgprice");
Long count= (Long) newEvents[0].get("mycount");</pre>
					<p>
						The runtime supplies the boxed <code class="literal">java.lang.Double</code> and <code class="literal">java.lang.Long</code> types as property values rather than primitive Java types. This is because aggregated values can return a <code class="literal">null</code> value to indicate that no data is available for aggregation. Also, in a select statement that computes expressions, the underlying event objects to <code class="literal">EventBean</code> instances are either of type <code class="literal">Object[]</code> (object-array) or of type <code class="literal">java.util.Map</code>.
					</p>
					<p>
						Use <code class="literal">statement.getEventType().getUnderlyingType()</code> to inspect the underlying type for all events delivered to listeners. Whether the runtime delivers Map or Object-array events to listeners can be specified as follows. If the statement provides the <code class="literal">@EventRepresentation(objectarray)</code> annotation the runtime delivers the output events as object array. If the statement provides the <code class="literal">@EventRepresentation(map)</code> annotation the runtime delivers output events as a Map. If neither annotation is provided, the runtime delivers the configured default event representation as discussed in <a class="xref" href="configuration.html#configuration-common-eventmeta-representation" title="17.4.9.1. Default Event Representation">Section 17.4.9.1, “Default Event Representation”</a>.
					</p>
					<p>
						Consider the next statement that specifies a wildcard selecting the same type of event:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from StockTickEvent where price &gt; 100</pre>
					<p>
						The property names and types provided by an <code class="literal">EventBean</code> query result row, as posted by the statement above are as follows:
					</p>
					<div class="table"><a id="d0e43959"></a>
						<p class="title"><b>Table 16.5. Properties Offered by Sample Wildcard-Select Statement</b></p>
						<div class="table-contents">
							<table summary="Properties Offered by Sample Wildcard-Select Statement" border="1">
								<colgroup>
									<col>
									<col>
									<col>
									<col>
								</colgroup>
								<thead>
									<tr>
										<th>Name</th>
										<th>Type</th>
										<th>Description</th>
										<th>Java code snippet</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td><code class="literal">symbol</code></td>
										<td>java.lang.String</td>
										<td>Value of symbol event property</td>
										<td>
											<pre class="synopsis">eventBean.get("symbol")</pre>
										</td>
									</tr>
									<tr>
										<td><code class="literal">price</code></td>
										<td>double</td>
										<td>Value of price event property</td>
										<td>
											<pre class="synopsis">eventBean.get("price")</pre>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div><br class="table-break">
					<p>
						As an alternative to querying individual event properties via the <code class="literal">get</code> methods, the <code class="literal">getUnderlying</code> method on <code class="literal">EventBean</code> returns the underlying object representing the statement result.
						In the sample statement that features a wildcard-select, the underlying event object is of type <code class="literal">org.sample.StockTickEvent</code>:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">StockTickEvent tick = (StockTickEvent) newEvents[0].getUnderlying();</pre>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-statement-eventtypepattern"></a>16.5.5.4. Pattern Example</h4>
							</div>
						</div>
					</div>
					<p>
						Composite events are events that aggregate one or more other events. Composite events are typically created by the runtime for statements that join two event streams, and for event patterns in which the causal events are retained and reported in a composite event. The example below shows such an event pattern.
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Look for a pattern where BEvent follows AEvent
select * from pattern [a=AEvent -&gt; b=BEvent]</pre>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Example listener code
public class MyUpdateListener implements UpdateListener {
  public void update(EventBean[] newData, EventBean[] oldData, EPStatement statement, EPRuntime runtime) {
    System.out.println("a event=" + newData[0].get("a"));
    System.out.println("b event=" + newData[0].get("b"));
  }
}</pre>
					<p>
						Note that the <code class="literal">update</code> method can receive multiple events at once as it accepts an array of <code class="literal">EventBean</code> instances. For example, a time batch window may post multiple events to listeners representing a batch of events received during a given time period.
					</p>
					<p>
						Pattern statements can also produce multiple events delivered to update listeners in one invocation. The pattern statement below, for instance, delivers an event for each A event that was not followed by a B event with the same <code class="literal">id</code> property within 60 seconds of the A event. The runtime may deliver all matching A events as an array of events in a single invocation of the <code class="literal">update</code> method of each listener to the statement:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern[every a=A -&gt; (timer:interval(60 sec) and not B(id=a.id))]</pre>
					<p>
						A code snippet out of a possible <code class="literal">UpdateListener</code> implementation to this statement that retrives the events as fragments may look as below:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EventBean a = (EventBean) newEvents[0].getFragment("a");
// ... or using a nested property expression to get a value out of A event...
double value = (Double) newEvent[0].get("a.value");</pre>
					<p>
						Some pattern objects return an array of events. An example is the unbound repeat operator. Here is a sample pattern that collects all A events until a B event arrives:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from pattern [a=A until b=B]</pre>
					<p>
						A possible code to retrieve different fragments or property values:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EventBean[] a = (EventBean[]) newEvents[0].getFragment("a");
// ... or using a nested property expression to get a value out of A event...
double value = (Double) newEvent[0].get("a[0].value");</pre>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-typeinfo"></a>16.5.6. Type Information</h3>
						</div>
					</div>
				</div><a id="d0e44061" class="indexterm"></a><a id="d0e44066" class="indexterm"></a><a id="d0e44069" class="indexterm"></a><a id="d0e44072" class="indexterm"></a>
				<p>
					The Esper compiler and runtime use the <code class="literal">EPType</code> interface for tracking all Java (or C# for .NET) type information. The <code class="literal">EPType</code> interface can be found in package <code class="literal">com.espertech.esper.common.client.type</code>.
				</p>
				<p>
					EPL uses three-valued logic and thus <code class="literal">null</code> is a viable type. More information can be found at <a class="xref" href="processingmodel.html#processingmodel_3valuedlogic" title="2.19. Basic Null">Section 2.19, “Basic Null”</a>. The null-type is represented by <code class="literal">EPTypeNull</code>.
				</p>
				<p>
					EPL supports un-parameterized types and a type that is not parameterized is represented by <code class="literal">EPTypeClass</code>.
				</p>
				<p>
					EPL also supports parameterized types and a type that is parameterized is represented by <code class="literal">EPTypeClassParameterized</code>. Since an instance of <code class="literal">java.lang.Class</code> does not provide information about actual type parameters (aka. type erasure)
					and since there is no null-type class the compiler and runtime use <code class="literal">EPType</code> instead of <code class="literal">java.lang.Class</code>.
				</p>
				<p>
					To obtain the event property type use the <code class="literal">getPropertyEPType</code> method of <code class="literal">EventType</code> or <code class="literal">EventPropertyDescriptor</code>. Please consult the JavaDoc for additional information.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-statement-annotation"></a>16.5.7. Interrogating Annotations</h3>
						</div>
					</div>
				</div><a id="d0e44129" class="indexterm"></a>
				<p>
					As discussed in <a class="xref" href="epl_clauses.html#epl-syntax-annotation" title="5.2.7. Annotation">Section 5.2.7, “Annotation”</a> an EPL annotation is an addition made to statement information. The API and examples to interrogate annotations are described here.
				</p>
				<p>
					You may use the <code class="literal">getAnnotations</code> method of <code class="literal">EPStatement</code> to obtain annotations specified for a statement. Or when compiling an EPL expression to a <code class="literal">EPStatementObjectModel</code> statement object model you may also query, change or add annotations.
				</p>
				<p>
					The following example code demonstrates iterating over an <code class="literal">EPStatement</code> statement's annotations and retrieving values:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String exampleEPL = "@Tag(name='direct-output', value='sink 1') select * from RootEvent";
Configuration configuration = new Configuration();
configuration.getCommon().addEventType("RootEvent", Collections.emptyMap()); // add an event type without properties
CompilerArguments compilerArguments = new CompilerArguments(configuration);
EPCompiled compiled = EPCompilerProvider.getCompiler().compile(stmt, compilerArguments);

EPDeployment deployment = runtime.getDeploymentService().deploy(compiled);
EPStatement stmt = deployment.getStatements()[0];
for (Annotation annotation : stmt.getAnnotations()) {
  if (annotation instanceof Tag) {
    Tag tag = (Tag) annotation;
    System.out.println("Tag name " + tag.name() + " value " + tag.value());
  }
}</pre>
				<p>
					The output of the sample code shown above is <code class="literal">Tag name direct-output value sink 1</code>.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-eventservice"></a>16.6. Processing Events and Time Using <code class="literal">EPEventService</code></h2>
					</div>
				</div>
			</div><a id="d0e44166" class="indexterm"></a>
			<p>
				The <code class="literal">EPEventService</code> interface is used to send events and advance time. Obtain the event service from a runtime by calling <code class="literal">getEventService</code> on <code class="literal">EPRuntime</code>.
			</p>
			<p>
				This section focuses on processing events. For more information on controlling time using the event service please skip forward to <a class="xref" href="apiruntime.html#apiruntime-time" title="16.9. Controlling Time-Keeping">Section 16.9, “Controlling Time-Keeping”</a>.
			</p>
			<p>
				Your application invokes any of the <code class="literal">sendEvent<span class="emphasis"><em>Type</em></span></code> methods listed below and must provide an event type name along with the actual event object:
			</p>
			<div class="table"><a id="apiruntime-eventservice-sendeventmethods"></a>
				<p class="title"><b>Table 16.6. Send-Event Methods</b></p>
				<div class="table-contents">
					<table summary="Send-Event Methods" border="1">
						<colgroup>
							<col>
							<col>
						</colgroup>
						<thead>
							<tr>
								<th>Method</th>
								<th>Description</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">sendEventBean(Object event, String eventTypeName)</pre>
								</td>
								<td>
									<p>Call when the event is a Bean-style event. The event type name should be associated to a class event representation.</p>
								</td>
							</tr>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">sendEventMap(Map&lt;String, Object&gt; event, String eventTypeName)</pre>
								</td>
								<td>
									<p>Call when the event is a map. The event type name should be associated to a map event representation.</p>
								</td>
							</tr>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">sendEventObjectArray(Object[] event, String eventTypeName);</pre>
								</td>
								<td>
									<p>Call when the event is an object-array. The event type name should be associated to an object-array event representation.</p>
								</td>
							</tr>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">sendEventXMLDOM(Node node, String eventTypeName);</pre>
								</td>
								<td>
									<p>Call when the event is a DOM-Node. The event type name should be associated to an XML event representation.</p>
								</td>
							</tr>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">void sendEventJson(String json, String jsonEventTypeName);</pre>
								</td>
								<td>
									<p>Call when the event is an JSON-formatted string-type document. The event type name should be associated to a JSON event representation.</p>
								</td>
							</tr>
							<tr>
								<td>
									<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">void sendEventAvro(Object avroGenericDataDotRecord, String avroEventTypeName);</pre>
								</td>
								<td>
									<p>Call when the event is an Avro object. The event type name should be associated to an Avro event representation.</p>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div><br class="table-break">
			<p>
				The <a class="xref" href="event_representation.html" title="Chapter 3. Event Representations">Chapter 3, <i>Event Representations</i></a> section explains the types of event representations.
			</p>
			<p>
				The below sample code assumes that the event type name <code class="literal">MarketDataBean</code> refers to a class event representation that matches the class <code class="literal">MarketDataBean</code>:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();
EPEventService eventService = runtime.getEventService();

// Send an example event containing stock market data
eventService.sendEventBean(new MarketDataBean("IBM", 75.0), "MarketDataBean");</pre>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
				<h2>Tip</h2>
				<p>
					Events, in theoretical terms, are observations of a state change that occurred in the past. Since you cannot change an event that happened in the past, events are best modelled as immutable objects.
				</p>
				<p>
					If you find that your application requires processing events and control over time only for specific deployments and not for other deployments, please read up on <a class="xref" href="apiruntime.html#apiruntime-stages" title="16.21. Stages">Section 16.21, “Stages”</a>.
				</p>
			</div>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="caution">
				<h2>Caution</h2>
				<p>
					The runtime relies on events that are sent into the runtime to not change their state. Typically, applications create a new event object for every new event, to represent that new event. Application should not modify an existing event that was sent into the runtime.
				</p>
			</div>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="important">
				<h2>Important</h2>
				<p>
					Another important method in the runtime interface are the <code class="literal">routeEvent<span class="emphasis"><em>Type</em></span></code> methods. These methods are designed for use by <code class="literal">UpdateListener</code> and
					subscriber implementations as well as runtime extensions that need to send events into a runtime to avoid the possibility of a stack overflow due to nested calls
					to <code class="literal">sendEvent</code> and to ensure correct processing of the current and routed event.
					Note that if outbound-threading is enabled, listeners and subscribers should use <code class="literal">sendEvent</code> and not <code class="literal">routeEvent</code>.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-eventservice-eventsender"></a>16.6.1. Event Sender</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">EventSender</code> interface processes event objects that are of a known type. This facility can reduce the overhead of event object reflection and type lookup as an event sender
					is always associated to a single concrete event type.
				</p>
				<p>
					Use the method <code class="literal">getEventSender(String eventTypeName) </code> to obtain an event sender for processing events of the named type:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EventSender sender = runtime.getEVentService().getEventSender("MyEvent");
sender.sendEvent(myEvent);</pre>
				<p>
					For events backed by a Java class (JavaBean events), the event sender ensures that the event object equals the underlying class, or implements or extends the underlying class
					for the given event type name.
				</p>
				<p>
					For events backed by a <code class="literal">java.util.Map</code> (Map events), the event sender does not perform any checking other than checking that the event object implements Map.
				</p>
				<p>
					For events backed by a <code class="literal">Object[]</code> (Object-array events), the event sender does not perform any checking other than checking that the event object implements Object[]. The array elements must be in the exact same order of properties as declared and array length must always be at least the number of properties declared.
				</p>
				<p>
					For JSON events, the event sender checks that the event object is a string-type value or is an <code class="literal">JsonEventUnderlying</code> object returned by the <code class="literal">parse</code> method of <code class="literal">EventSenderJson</code>. The JSON document should match the fields defined in <code class="literal">create schema</code>.
				</p>
				<p>
					For Avro events backed by a Apache Avro <code class="literal">GenericData.Record</code>, the event sender does not perform any checking other than checking that the event object is a GenericData.Record. The schema associated to the record should match the event type's Avro schema.
				</p>
				<p>
					For events backed by a org.w3c.Node (XML DOM events), the event sender checks that the root element name equals the root element name for the event type.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-eventservice-unmatched"></a>16.6.2. Receiving Unmatched Events</h3>
						</div>
					</div>
				</div><a id="d0e44341" class="indexterm"></a>
				<p>
					Your application can register an implementation of the <code class="literal">UnmatchedListener</code> interface with the event service by calling the <code class="literal">setUnmatchedListener</code> method to receive events that were not matched by any statement.
				</p>
				<p>
					Events that can be unmatched are all events that your application sends into the runtime via one of the <code class="literal">sendEvent</code> or <code class="literal">routeEvent</code> methods, or that have been generated via an <code class="literal">insert into</code> clause.
				</p>
				<p>
					For an event to become unmatched by any statement, the event must not match any statement's event stream filter criteria. Note that the EPL <code class="literal">where</code> clause or <code class="literal">having</code> clause are not considered part of the filter criteria for a stream, as explained by example below.
				</p>
				<p>
					In the following statement a MyEvent event with a 'quantity' property value of 5 or less does not match this statement's event stream filter criteria. The runtime delivers such an event to the registered <code class="literal">UnmatchedListener</code> instance provided no other statement matches on the event:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from MyEvent(quantity &gt; 5)</pre>
				<p>
					For patterns, if no pattern sub-expression is active for an event type, an event of that type also counts as unmatched in regards to the pattern statement.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-fireandforget"></a>16.7. Execute Fire-and-Forget Queries Using <code class="literal">EPFireAndForgetService</code></h2>
					</div>
				</div>
			</div><a id="d0e44385" class="indexterm"></a>
			<p>
				The <code class="literal">EPFireAndForgetService</code> interface offers methods to execute fire-and-forget queries. Obtain the fire-and-forget service from a runtime by calling <code class="literal">getFireAndForgetService</code> on <code class="literal">EPRuntime</code>.
			</p>
			<p>
				As your application may not require streaming results and may not know each statement in advance, the fire-and-forget query facility provides for ad-hoc on-demand execution of an EPL query.
			</p>
			<p>
				Fire-and-forget queries are not continuous in nature: The fire-and-forget query runtime executes the query once and returns all result rows to the application. Fire-and-forget query execution is very lightweight as the runtime performs no statement deployment and the query leaves no traces within the runtime.
			</p>
			<p>
				Esper provides the facility to explicitly index named windows and tables to speed up fire-and-forget queries and statements. Please consult <a class="xref" href="nwtable.html#named_explicit_index" title="6.9. Explicitly Indexing Named Windows and Tables">Section 6.9, “Explicitly Indexing Named Windows and Tables”</a> for more information.
			</p>
			<p>
				When named windows and tables are used with contexts and context partitions, the APIs to identify, filter and select context partitions for fire-and-forget queries can be found in <a class="xref" href="apiruntime.html#apiruntime-contextpartitionselection" title="16.16. Context Partition Selection">Section 16.16, “Context Partition Selection”</a>.
			</p>
			<p>
				There are three ways to run fire-and-forget queries:
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
				<ol>
					<li>
						<p>
							Use the <code class="literal">executeQuery</code> method to executes a given fire-and-forget query exactly once, see <a class="xref" href="apiruntime.html#apiruntime-fireandforget-single" title="16.7.1. Fire-and-forget Query Single Execution">Section 16.7.1, “Fire-and-forget Query Single Execution”</a>.
						</p>
					</li>
					<li>
						<p>
							Use the <code class="literal">prepareQuery</code> method to prepare a given fire-and-forget query such that the same query can be executed multiple times, see <a class="xref" href="apiruntime.html#apiruntime-fireandforget-prepared" title="16.7.2. Fire-and-forget Query Prepared Unparameterized Execution">Section 16.7.2, “Fire-and-forget Query Prepared Unparameterized Execution”</a>.
						</p>
					</li>
					<li>
						<p>
							Use the <code class="literal">prepareQueryWithParameters</code> method to prepare a given fire-and-forget query that may have substitution parameters such that the same query can be parameterized and executed multiple times without repeated parsing, see <a class="xref" href="apiruntime.html#apiruntime-fireandforget-preparedparameterized" title="16.7.3. Fire-and-forget Query Prepared Parameterized Execution">Section 16.7.3, “Fire-and-forget Query Prepared Parameterized Execution”</a>
						</p>
					</li>
				</ol>
			</div>
			<p>
				If your application must execute the same fire-and-forget query multiple times with different parameters use <code class="literal">prepareQueryWithParameters</code>.
			</p>
			<p>
				If your application must execute the same fire-and-forget query multiple times without parameters use either <code class="literal">prepareQuery</code> or <code class="literal">prepareQueryWithParameters</code> and specify no substitution parameters.
			</p>
			<p>
				By using any of the <code class="literal">prepare...</code> methods the runtime can load the byte code for the query once and reuse the byte code and thereby speed up repeated execution.
			</p>
			<p>
				The following limitations apply:
			</p>
			<div class="itemizedlist">
				<ul>
					<li>
						<p>
							A fire-and-forget only evaluates against the named windows and tables that your application creates. Fire-and-forget queries may not specify any other streams or application event types.
						</p>
					</li>
					<li>
						<p>
							The following clauses are not allowed in fire-and-forget EPL queries: <code class="literal">insert into</code> and <code class="literal">output</code>.
						</p>
					</li>
					<li>
						<p>
							Data windows and patterns are not allowed to appear in fire-and-forget queries.
						</p>
					</li>
					<li>
						<p>
							Fire-and-forget EPL may not perform subqueries.
						</p>
					</li>
					<li>
						<p>
							The <code class="literal">previous</code> and <code class="literal">prior</code> functions may not be used.
						</p>
					</li>
				</ul>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-fireandforget-single"></a>16.7.1. Fire-and-forget Query Single Execution</h3>
						</div>
					</div>
				</div>
				<p>
					Use the <code class="literal">executeQuery</code> method for executing a fire-and-forget query once. For repeated execution, please consider any of the <code class="literal">prepare...</code> methods instead.
				</p>
				<p>
					The next program listing runs a fire-and-forget query against a named window <code class="literal">MyNamedWindow</code> and prints a column of each row result of the query (this sample uses the compiler runtime-path):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String query = "select * from MyNamedWindow";
CompilerArguments compilerArguments = new CompilerArguments();
compilerArguments.getPath().add(runtime.getRuntimePath());
EPCompiled compiled = EPCompilerProvider.getCompiler().compileQuery(query, compilerArguments);

EPFireAndForgetQueryResult result = runtime.getFireAndForgetService().executeQuery(compiled);
for (EventBean row : result.getArray()) {
  System.out.println("name=" + row.get("name"));
}</pre>
				<p>
					For executing a fire-and-forget against a table please put the table name into the <code class="literal">from</code>-clause instead.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-fireandforget-prepared"></a>16.7.2. Fire-and-forget Query Prepared Unparameterized Execution</h3>
						</div>
					</div>
				</div>
				<p>
					Prepared fire-and-forget queries are designed for repeated execution and may perform better then the dynamic single-execution method if running the same query multiple times.
					For use with parameter placeholders please see <a class="xref" href="apiruntime.html#apiruntime-fireandforget-preparedparameterized" title="16.7.3. Fire-and-forget Query Prepared Parameterized Execution">Section 16.7.3, “Fire-and-forget Query Prepared Parameterized Execution”</a>.
				</p>
				<p>
					The next code snippet demonstrates prepared fire-and-forget queries without parameter placeholder:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String query = "select * from MyNamedWindow where orderId = '123'";
CompilerArguments compilerArguments = new CompilerArguments();
compilerArguments.getPath().add(runtime.getRuntimePath());
EPCompiled compiled = EPCompilerProvider.getCompiler().compileQuery(query, compilerArguments);
						
EPFireAndForgetPreparedQuery prepared = runtime.getFireAndForgetService().prepareQuery(compiled);
EPFireAndForgetQueryResult result = prepared.execute();

// ...later on execute once more ...
prepared.execute();	// execute a second time</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-fireandforget-preparedparameterized"></a>16.7.3. Fire-and-forget Query Prepared Parameterized Execution</h3>
						</div>
					</div>
				</div>
				<p>
					Please see the compiler documentation for specifying substitution parameters.
				</p>
				<p>
					All substitution parameters must be replaced by actual values before a fire-and-forget query with substitution parameters can be executed. Substitution parameters can be replaced with an actual value using the <code class="literal">setObject</code> method for each index or name. Substitution parameters can be set to new values and the query executed more than once.
				</p>
				<p>
					While the <code class="literal">setObject</code> method allows substitution parameters to assume any actual value including application Java objects or enumeration values, the application must provide the correct type of substitution parameter that matches the type that
					was specified, if any, and the requirements of the expression the parameter resides in.
				</p>
				<p>
					The next program listing runs a prepared and parameterized fire-and-forget query against a named window <code class="literal">MyNamedWindow</code> (this example does not assign names to substitution parameters):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String query = "select * from MyNamedWindow where orderId = ?::string";
CompilerArguments compilerArguments = new CompilerArguments();
compilerArguments.getPath().add(runtime.getRuntimePath());
EPCompiled compiled = EPCompilerProvider.getCompiler().compileQuery(query, compilerArguments);

EPFireAndForgetPreparedQueryParameterized prepared = runtime.getFireAndForgetService().prepareQueryWithParameters(query);

// Set the required parameter values before each execution
prepared.setObject(1, "123");
EPFireAndForgetQueryResult result = runtime.getFireAndForgetService().executeQuery(prepared);

// ...execute a second time with new parameter values...
prepared.setObject(1, "456");
result = runtime.getFireAndForgetService().executeQuery(prepared);</pre>
				<p>
					This second example uses the <code class="literal">in</code> operator and has multiple parameters:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String query = "select * from MyNamedWindow where orderId in (?::string[]) and price &gt; ?::double";
CompilerArguments compilerArguments = new CompilerArguments();
compilerArguments.getPath().add(runtime.getRuntimePath());
EPCompiled compiled = EPCompilerProvider.getCompiler().compileQuery(query, compilerArguments);

EPFireAndForgetPreparedQueryParameterized prepared = runtime.getFireAndForgetService().prepareQueryWithParameters(compiled);
prepared.setObject(1, new String[] {"123", "456"});
prepared.setObject(2, 1000.0);</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-fireandforget-fromisoptional"></a>16.7.4. The <span class="emphasis"><em>From</em></span>-Clause is Optional</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">from</code>-clause in EPL is optional and is only required for subqueries. You may execute fire-and-forget queries without a <code class="literal">from</code>-clause. For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select 1 as value</pre>
				<p>
					You may use fire-and-forget queries to obtain information about the current context partitions. More information can be found at <a class="xref" href="context.html#context_outputinitiated" title="4.5. Output When a Context Partition Starts (Non-Overlapping Context) or Initiates (Overlapping Context)">Section 4.5, “Output When a Context Partition Starts (Non-Overlapping Context) or Initiates (Overlapping Context)”</a>. For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">context CtxPerOrder select context.orderEvent as orderEvent</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-fireandforget-fromcansql"></a>16.7.5. The <span class="emphasis"><em>From</em></span>-Clause can Access Relational Data via SQL</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">from</code>-clause can have an SQL query:
				</p>
				<pre class="synopsis"><code class="literal">... from sql:</code><span class="emphasis"><em>database_name</em></span><code class="literal"> [" </code><span class="emphasis"><em>parameterized_sql_query</em></span><code class="literal"> "]</code></pre>
				<p>
					The Esper runtime executes such fire-and-forget queries with SQL using the JDBC API. Please also refer to <a class="xref" href="epl_clauses.html#histdata_overview" title="5.13. Accessing Relational Data via SQL">Section 5.13, “Accessing Relational Data via SQL”</a> for more information.
				</p>
				<p>
					The sample EPL below returns the results of an SQL query against the database named <code class="literal">MyCustomerDB</code> and table <code class="literal">Customer</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from sql:MyCustomerDB ['select cust_name from Customer where cust_id = 10']</pre>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
					<h2>Tip</h2>
					<div class="itemizedlist">
						<ul>
							<li>
								<p>
									Use prepared execution (unparameterized or parameterized) when executing the same SQL query multiple times with same or different parameters.
									This allows the Esper runtime to reuse the JDBC <code class="literal">java.sql.Connection</code> and JDBC <code class="literal">PreparedStatement</code>.
									EPL Expressions including expressions with (public) variables and substitution parameters can be placed within <code class="literal">${...}</code> within the SQL text.
								</p>
							</li>
							<li>
								<p>
									To execute a query once an application can use single execution (see above). In single execution the runtime obtains a new JDBC <code class="literal">java.sql.Connection</code>, creates a JDBC <code class="literal">PreparedStatement</code> and discards the JDBC connection and JDBC statement after execution. This is not recommended for best performance.
								</p>
							</li>
						</ul>
					</div>
				</div>
				<p>
					This code snippet illustrates executing the SQL query by fire-and-forget API prepared unparameterized execution:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String query = "select * from sql:MyCustomerDB ['select cust_name from Customer where cust_id = 10";
EPCompiled compiled = EPCompilerProvider.getCompiler().compileQuery(query, new CompilerArguments());
EPFireAndForgetPreparedQuery prepared = runtime.getFireAndForgetService().prepareQuery(compiled);
EPFireAndForgetQueryResult result = prepared.execute();

// ...close() ...
prepared.close();	// close when done executing</pre>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="warning">
					<h2>Warning</h2>
					<p>
						Call the <code class="literal">close</code> method of <code class="literal">EPFireAndForgetPreparedQuery</code> and <code class="literal">EPFireAndForgetPreparedQueryParameterized</code>
						to release JDBC resources held by the runtime.
					</p>
				</div>
				<p>
					The following limitations apply:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							<p>
								Joins are not allowed when using <code class="literal">sql:</code> SQL queries in the <code class="literal">from</code>-clause however the SQL itself can be any SQL including a join.
							</p>
						</li>
						<li>
							<p>
								A <code class="literal">context</code> cannot be specified.
							</p>
						</li>
					</ul>
				</div>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-threading"></a>16.8. Runtime Threading and Concurrency</h2>
					</div>
				</div>
			</div><a id="d0e44667" class="indexterm"></a>
			<p>
				For NEsper .NET also see <a class="xref" href="">???</a>.
			</p>
			<p>
				The runtime is designed from the ground up to operate as a component to multi-threaded, highly-concurrent applications that require efficient use of Java VM resources. In addition, multi-threaded execution requires guarantees in predictability of results and deterministic processing. This section discusses these concerns in detail.
			</p>
			<p>
				In Esper, a runtime instance is a unit of separation. Applications can obtain and discard (initialize) one or more runtime instances within the same Java VM and can provide the same or different configurations to each instance. A runtime instance shares resources between statements by means of named windows, tables and variables.
			</p>
			<p>
				Applications can use Esper APIs to concurrently, by multiple threads of execution, perform such functions as deploying modules, or sending events into the runtime for processing. Applications can use application-managed threads or thread pools or any set of same or different threads of execution with any of the public runtime APIs. There are no restrictions towards threading other than those noted in specific sections of this document.
			</p>
			<p>
				The runtime does not prescribe a specific threading model. Applications using Esper retain full control over threading, allowing a runtime to be easily embedded and used as a component or library in your favorite Java container or process.
			</p>
			<p>
				In the default configuration it is up to the application code to use multiple threads for processing events by the runtime, if so desired. All event processing takes places within your application thread call stack. The exception is timer-based processing if your runtime relies on the internal timer (default). If your application relies on external timer events instead of the internal timer then there need not be any runtime-managed internal threads.
			</p>
			<p>
				The fact that event processing can take place within your application thread's call stack makes developing applications with the Esper runtime easier: Any common Java integrated development environment (IDE) can host a compiler and runtime instance. This allows developers to easily set up test cases, debug through listener code and inspect input or output events, or trace their call stack.
			</p>
			<p>
				In the default configuration, each runtime maintains a single timer thread (internal timer) providing for time or schedule-based processing within the runtime. The default resolution at which the internal timer operates is 100 milliseconds. The internal timer thread can be disabled and applications can instead advance time to perform timer or scheduled processing at the resolution required by an application.
			</p>
			<p>
				A runtime performs minimal locking to enable high levels of concurrency. A runtime locks on the combination of query and context partition to protect context partition resources. For example, two statements with three partitions each have a total of six locks. For stateless EPL select-statements the runtime does not use a context-partition lock and operates lock-free for the context partition. For stateful statements, the maximum (theoretical) degree of parallelism is 2^31-1 (2,147,483,647) parallel threads working to process a single statement under a hash segmented context.
			</p>
			<p>
				For named windows and tables, <code class="literal">on-select</code>, <code class="literal">on-merge</code>, <code class="literal">on-update</code> and <code class="literal">on-delete</code> all execute under the same lock as the partition of the named window or table.
				Any <code class="literal">insert into</code> produces a new event for the work queue and does not lock the target of the insert-into.
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
				<h2>Tip</h2>
				<p>
					For logging of lock activity please enable runtime lock activity logging as described in <a class="xref" href="configuration.html#configuration-runtime-logging-lockactivity" title="17.6.2.3. Lock Activity Logging">Section 17.6.2.3, “Lock Activity Logging”</a>.
				</p>
			</div>
			<p>
				You may turn off context partition locking runtime-wide (also read the caution notice) as described in <a class="xref" href="configuration.html#configuration-runtime-execution-disablelock" title="17.6.10.4. Disable Locking">Section 17.6.10.4, “Disable Locking”</a>. You may disable context partition locking for a given statement by providing the <code class="literal">@NoLock</code> annotation as part of your EPL. Note, Esper provides the <code class="literal">@NoLock</code> annotation for the purpose of identifying locking overhead, or when your application is single-threaded, or when using an external mechanism for concurrency control or for example with virtual data windows or plug-in data windows to allow customizing concurrency for a given statement or named window. Using this annotation may have unpredictable results unless your application is taking concurrency under consideration.
			</p>
			<p>
				For a runtime to produce predictable results from the viewpoint of listeners to statements, a runtime by default ensures that
				it dispatches statement result events to listeners in the order in which a statement produced result events. Applications that require the highest possible concurrency and do not require predictable order of delivery of events to listeners, this feature can be turned off via configuration, see
				<a class="xref" href="configuration.html#configuration-runtime-threading-dispatch" title="17.6.1.1. Preserving the Order of Events Delivered to Listeners">Section 17.6.1.1, “Preserving the Order of Events Delivered to Listeners”</a>. For example, assume thread T1 processes an event applied to statement S producing output event O1. Assume thread T2 processes another event applied to statement S and produces output event O2. The runtime employs a configurable latch system to ensure that listeners to statement S receive and may complete processing of O1 before receiving O2. When using outbound threading (advanced threading options) or changing the configuration this guarantee is weakened or removed.
			</p>
			<p>
				In multithreaded environments, when one or more statements make result events available via the <code class="literal">insert into</code> clause to further statements, the runtime preserves the order of events inserted into the generated insert-into stream, allowing statements that consume other statement's events to behave deterministic. This feature can also be turned off via configuration, see <a class="xref" href="configuration.html#configuration-runtime-threading-insertinto" title="17.6.1.2. Preserving the Order of Events for Insert-Into Streams">Section 17.6.1.2, “Preserving the Order of Events for Insert-Into Streams”</a>. For example, assume thread T1 processes an event applied to statement S and thread T2 processes another event applied to statement S. Assume statement S inserts into stream ST. T1 produces an output event O1 for processing by consumers of ST1 and T2 produces an output event O2 for processing by consumers of ST. The runtime employs a configurable latch system such that O1 is processed before O2 by consumers of ST. When using route execution threading (advanced threading options) or changing the configuration this guarantee is weakened or
				removed.
			</p>
			<p>
				We generally recommended that listener implementations block minimally or do not block at all. By implementing listener code as non-blocking code execution threads can often achieve higher levels of concurrency.
			</p>
			<p>
				We recommended that, when using a single listener or subscriber instance to receive output from multiple statements, that the listener or subscriber code is multithread-safe. If your application has shared state between
				listener or subscriber instances then such shared state should be thread-safe.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-threading-advanced"></a>16.8.1. Advanced Threading</h3>
						</div>
					</div>
				</div>
				<p>
					In the default configuration the same application thread that invokes any of the <code class="literal">sendEvent</code> methods will process the event fully and also deliver output events to listeners and subscribers. By default the single internal timer thread based on system time performs time-based processing and delivery of time-based results.
				</p>
				<p>
					This default configuration reduces the processing overhead associated with thread context switching, is lightweight and fast and works well in many environments such as J2EE, server or client. Latency and throughput requirements are largely use case dependent, and Esper provides runtime-level facilities for controlling concurrency that are described next.
				</p>
				<p>
					<span class="emphasis"><em>Inbound Threading</em></span> queues all incoming events: A pool of runtime-managed threads performs the event processing. The application thread that sends an event via any of the <code class="literal">sendEvent</code> methods returns without blocking.
				</p>
				<p>
					<span class="emphasis"><em>Outbound Threading</em></span> queues events for delivery to listeners and subscribers, such that slow or blocking listeners or subscribers do not block event processing.
				</p>
				<p>
					<span class="emphasis"><em>Timer Execution Threading</em></span> means time-based event processing is performed by a pool of runtime-managed threads. With this option the internal timer thread (or external timer event) serves only as a metronome, providing units-of-work to the runtime-managed threads in the timer execution pool, pushing threading to the level of each statement for time-based execution.
				</p>
				<p>
					<span class="emphasis"><em>Route Execution Threading</em></span> means that the thread sending in an event via any of the <code class="literal">sendEvent</code> methods (or the inbound threading pooled thread if inbound threading is enabled) only identifies and pre-processes an event, and a pool of runtime-managed threads handles the actual processing of the event for each statement, pushing threading to the level of each statement for event-arrival-based execution.
				</p>
				<p>
					The runtime starts runtime-managed threads as daemon threads when the runtime instance is first obtained. The runtime stops runtime-managed threads when the runtime instance is destroyed via the <code class="literal">destroy</code> method. When the runtime is initialized via the <code class="literal">initialize</code> method the existing runtime-managed threads are stopped and new threads are created. When shutting down your application, use the <code class="literal">destroy</code> method to stop runtime-managed threads.
				</p>
				<p>
					Note that the options discussed herein may introduce additional processing overhead into your system, as each option involves work queue management and thread context switching.
				</p>
				<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
					<h2>Note</h2>
					<p>
						If your use cases require ordered processing of events or do not tolerate disorder, the threading options described herein are not the right choice.
					</p>
					<p>
						For enforcing a processing order within a given criteria, your application must enforce such processing order. Esper does not enforce order of processing if you enable inbound or route threading.
						Your application code could, for example, utilize a thread per group of criteria keys, a latch per criteria key, or a queue per criteria key, or use Java's completion service, all depending on your ordering requirements.
					</p>
				</div>
				<p>
					If your use cases require loss-less processing of events, wherein the threading options mean that events are held in an in-memory queue, the threading options described herein may not be the right choice.
				</p>
				<p>
					Care should be taken to consider arrival rates and queue depth. Threading options utilize unbound queues or capacity-bound queues with blocking-put, depending on your configuration, and may therefore introduce an overload or blocking situation to your application. You may use the service provider interface as outlined below to manage queue sizes, if required, and to help tune the runtime to your application needs. Consider throttling down the event send rate when the API (see below) indicates that events are getting queued.
				</p>
				<p>
					All threading options are on the level of a runtime. If you require different threading behavior for certain statements then consider using multiple runtimes, consider using the <code class="literal">routeEvent</code> method or consider
					using application threads instead.
				</p>
				<p>
					Please consult <a class="xref" href="configuration.html#configuration-runtime-threading" title="17.6.1. Runtime Settings Related to Concurrency and Threading">Section 17.6.1, “Runtime Settings Related to Concurrency and Threading”</a> for instructions on how to configure threading options. Threading options take effect at runtime initialization time.
				</p>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-threading-advanced-inbound"></a>16.8.1.1. Inbound Threading</h4>
							</div>
						</div>
					</div>
					<p>
						With inbound threading a runtime places inbound events in a queue for processing by one or more runtime-managed threads other than the delivering application threads.
					</p>
					<p>
						The delivering application thread uses one of the <code class="literal">sendEvent<span class="emphasis"><em>Type</em></span></code> methods on <code class="literal">EPEventService</code> to deliver events or may also use the <code class="literal">sendEvent</code> method on a <code class="literal">EventSender</code>. The runtime receives the event and places the event into a queue, allowing the delivering thread to continue and not block while the event is being processed and results are delivered.
					</p>
					<p>
						Events that are sent into the runtime via one of the <code class="literal">routeEvent</code> methods are not placed into queue but processed by the same thread invoking the <code class="literal">routeEvent</code> operation.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-threading-advanced-outbound"></a>16.8.1.2. Outbound Threading</h4>
							</div>
						</div>
					</div>
					<p>
						With outbound threading a runtime places outbound events in a queue for delivery by one or more runtime-managed threads other than the processing thread originating the result.
					</p>
					<p>
						With outbound threading your listener or subscriber class receives statement results from one of the runtime-managed threads in the outbound pool of threads. This is useful when you expect your listener or subscriber code to perform significantly blocking operations and you do not want to hold up event processing.
					</p>
					<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
						<h2>Note</h2>
						If outbound-threading is enabled, listeners and subscribers that send events back into the runtime should use the <code class="literal">sendEvent</code> method and not the <code class="literal">routeEvent</code> method.
					</div>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-threading-advanced-timer-exec"></a>16.8.1.3. Timer Execution Threading</h4>
							</div>
						</div>
					</div>
					<p>
						With timer execution threading an runtime places time-based work units into a queue for processing by one or more runtime-managed threads other than the internal timer thread or the application thread that sends an external timer event.
					</p>
					<p>
						Using timer execution threading the internal timer thread (or thread delivering an external timer event) serves to evaluate which time-based work units must be processed. A pool of runtime-managed threads performs the actual processing of time-based work units and thereby offloads the work from the internal timer thread (or thread delivering an external timer event).
					</p>
					<p>
						Enable this option as a tuning parameter when your statements utilize time-based patterns or data windows. Timer execution threading is fine grained and works on the level of a time-based schedule in combination with a statement.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-threading-advanced-route-exec"></a>16.8.1.4. Route Execution Threading</h4>
							</div>
						</div>
					</div>
					<p>
						With route execution threading an runtime identifies event-processing work units based on the event and statement combination. It places such work units into a queue for processing by one or more runtime-managed threads other than the thread that originated the event.
					</p>
					<p>
						While inbound threading works on the level of an event, route execution threading is fine grained and works on the level of an event in combination with a statement.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-threading-management"></a>16.8.1.5. Threading Service Provider Interface</h4>
							</div>
						</div>
					</div>
					<p>
						The service-provider interface <code class="literal">EPRuntimeSPI</code> is an extension API that allows to manage runtime-level queues and thread pools (Extension APIs are subject to change between release versions).
					</p>
					<p>
						The following code snippet shows how to obtain the <code class="literal">BlockingQueue&lt;Runnable&gt;</code> and the <code class="literal">ThreadPoolExecutor</code> for the managing the queue and thread pool responsible for inbound threading:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPRuntimeSPI spi = (EPRuntimeSPI) runtime;
int queueSize = spi.getThreadingService().getInboundQueue().size();
ThreadPoolExecutor threadpool = spi.getThreadingService().getInboundThreadPool();</pre>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-processingorder"></a>16.8.2. Processing Order</h3>
						</div>
					</div>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-processingorder-competingstmt"></a>16.8.2.1. Competing Statements</h4>
							</div>
						</div>
					</div>
					<p>
						This section discusses the order in which N competing statements that all react to the same arriving event execute.
					</p>
					<p>
						The runtime, by default, does not guarantee to execute competing statements in any particular order unless using @Priority. We therefore recommend that an application does not rely on the order of execution of statements by the runtime, since that best shields the behavior of an application from changes in the order that statements may get created by your application or by threading configurations that your application may change at will.
					</p>
					<p>
						If your application requires a defined order of execution of competing statements, use the @Priority EPL syntax to make the order of execution between statements well-defined (requires that you set the prioritized-execution configuration setting). And the @Drop can make a statement preempt all other lowered priority ones that then won't get executed for any matching events.
					</p>
				</div>
				<div class="sect3" lang="en-US">
					<div class="titlepage">
						<div>
							<div>
								<h4 class="title"><a id="apiruntime-processingorder-eventdepth"></a>16.8.2.2. Processing Principles of Events and Listener Updates</h4>
							</div>
						</div>
					</div>
					<p>
						The runtime processes event by event. It only processes the next event when processing of the current event has completed.
					</p>
					<p>
						For the purpose of processing event-by-event, the runtime maintains a thread-specific ordered <span class="emphasis"><em>work queue</em></span>.
						In the default configuration the order of events in the work queue is dictated by the order of execution of insert-into.
					</p>
					<p>
						New events get added to the end of the work queue (exceptions highlighted below) unless events have an <code class="literal">event-precedence</code> (see below).
						The runtime works off each event in the work queue completely, beginning with the oldest event, before processing the next newer event in the work queue.
					</p>
					<p>
						The runtime processes the current event against all statements completely before delivering results to listeners and subscribers and before processing the next event. This is true regardless whether a given event was sent in via the API or whether the event was produced by a statement and <code class="literal">insert-into</code>. The order is:
					</p>
					<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
						<ol>
							<li>
								<p>
									Process a given event against only those statement context partitions that need to see the event (see information on filter indexes).
								</p>
							</li>
							<li>
								<p>
									Dispatch statement results to listeners and subscribers.
								</p>
							</li>
						</ol>
					</div>
					<p>
						For example, assume three statements named <code class="literal">statement-1</code>, <code class="literal">statement-2</code> and <code class="literal">statement-3</code>:
					</p>
					<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">@name('statement-1') select * from MyEvent;
@name('statement-2') insert into ABCStream select * from MyEvent;
@name('statement-3') select * from ABCStream;</pre>
					<p>
						When a <code class="literal">MyEvent</code> event arrives, the order of processing is:
					</p>
					<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="orderedlist">
						<ol>
							<li>
								<p>
									The runtime processes <code class="literal">statement-1</code> and <code class="literal">statement-2</code> in any order (since there is no @priority set, see priority related documentation).
								</p>
								<div class="itemizedlist">
									<ul>
										<li>
											<p>
												For <code class="literal">statement-1</code> the runtime determines whether listeners are attached and if yes buffers the dispatch for delivery to listeners.
											</p>
										</li>
										<li>
											<p>
												For <code class="literal">statement-2</code> the runtime determines whether listeners are attached and if yes buffers the dispatch for delivery to listeners.
												The runtime also produces an <code class="literal">ABCStream</code> event and adds it to the work queue.
											</p>
										</li>
									</ul>
								</div>
							</li>
							<li>
								<p>
									The runtime invokes the listeners to <code class="literal">statement-1</code> and <code class="literal">statement-2</code> (default configuration, not considing all threading configurations).
								</p>
							</li>
							<li>
								<p>
									The runtime picks up the <code class="literal">ABCStream</code> event from the work queue and processes <code class="literal">statement-3</code> .
								</p>
							</li>
							<li>
								<p>
									The runtime invokes the listeners to <code class="literal">statement-3</code>.
								</p>
							</li>
						</ol>
					</div>
					<p>
						Among all events generated by insert-into of statements and the events routed into the runtime via the <code class="literal">routeEvent</code> method, all events that insert-into a named window or table are processed first in the order generated. All other events are processed thereafter in the order they were generated (except when using <code class="literal">event-precedence)</code>.
					</p>
					<p>
						If your application requires a defined order of processing among the events that are generated by <code class="literal">insert-into</code>, use the <code class="literal">event-precedence </code> syntax. Please see <a class="xref" href="epl_clauses.html#insert-into-eventprecedence" title="5.10.10. Insert Into and Event Precedence">Section 5.10.10, “Insert Into and Event Precedence”</a> and <a class="xref" href="configuration.html#configuration-runtime-execution-eventprecedence" title="17.6.10.2. Event-Precedence Execution">Section 17.6.10.2, “Event-Precedence Execution”</a> for more information.
					</p>
					<p>
						When enabling timer or route execution threading as explained under advanced threading options then the runtime does not make any guarantee to the processing order except that is will prioritize events inserted into a named window.
					</p>
				</div>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-time"></a>16.9. Controlling Time-Keeping</h2>
					</div>
				</div>
			</div><a id="d0e45014" class="indexterm"></a><a id="d0e45019" class="indexterm"></a><a id="d0e45022" class="indexterm"></a>
			<p>
				There are two modes for a runtime to keep track of time: The internal timer based on JVM system time (the default), and externally-controlled (aka. event time) time giving your application full control over the concept of time within a runtime.
			</p>
			<p>
				By default the internal timer provides time and evaluates schedules. External clocking i.e. event time can be used to supply time ticks to the runtime instead.
				The latter is useful for when events themselves provide the time to advance. External clocking also helps in testing time-based event sequences or for synchronizing the runtime with an external time source.
			</p>
			<p>
				The internal timer relies on the <code class="literal">java.util.concurrent.ScheduledThreadPoolExecutor</code> class for time tick events. The next section describes timer resolution for the internal timer, by default set to 100 milliseconds but is configurable via the threading options. When using externally-controlled time the timer resolution is in your control.
			</p>
			<p>
				To disable the internal timer and use externally-provided time instead, there are two options. The first option is to use the configuration API at runtime initialization time. The second option toggles on and off the internal timer at runtime, via special timer control events that are sent into the runtime like any other event.
			</p>
			<p>
				If using a timer execution thread pool as discussed above, the internal timer or external time event provide the schedule evaluation however do not actually perform the time-based processing. The time-based processing is performed by the threads in the timer execution thread pool.
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
				<h2>Tip</h2>
				<p>
					External and internal/system time is the same internally to the runtime thus the runtime behaves the same whether using external or internal timer.
				</p>
			</div>
			<p>
				This code snippet shows the use of the configuration API to disable the internal timer and thereby turn on externally-provided time (see the Configuration section for configuration via XML file):
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration config = new Configuration();
config.getRuntime().getThreading().setInternalTimerEnabled(false);
EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime(config);</pre>
			<p>
				After disabling the internal timer, it is wise to set a defined time so that any statements created thereafter start relative to the time defined. Use the <code class="literal">advanceTime</code> method to indicate current time to the runtime
				and to move time forward for the runtime (a.k.a application-time model).
			</p>
			<p>
				This code snippet obtains the current time and advances time:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">long timeInMillis = System.currentTimeMillis();
runtime.getEventService().advanceTime(timeInMillis);</pre>
			<p>
				To enable or disable the internal timer by API call use the <code class="literal">clockExternal</code> and <code class="literal">clockInternal</code> methods of <code class="literal">EPEventService</code>.
			</p>
			<p>
				The next code snippet demonstrates toggling to external time:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();
EPEventService eventService = runtime.getEventService();
// switch to external clocking
eventService.clockExternal();</pre>
			<p>
				The <code class="literal">advanceTime</code> method moves the time forward. All aspects of runtime current time related to statements and patterns are driven by the time that your application advances to.
			</p>
			<p>
				The next example sequence of instructions sets time to zero, then creates a statement, then moves time forward to 1 seconds later and then 6 seconds later:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Set start time at zero.
runtime.getEventService().advanceTime(0);

// deploy a module here
// sample EPL: select current_timestamp() as ct from pattern[every timer:interval(1 minute)]
runtime.getDeploymentService().deploy(compiled); // compiled is a module you compiled earlier

// move time forward 1 second
runtime.getEventService().advanceTime(1000);

// move time forward 5 seconds
runtime.getEventService().advanceTime(6000);</pre>
			<p>
				When advancing time your application should make sure values are ascending. That is, each time value should be either the same value or a larger value then the prior value provided.
			</p>
			<p>
				Your application may use the <code class="literal">getNextScheduledTime</code> method in <code class="literal">EPEventService</code> to determine the earliest time a schedule for any statement requires evaluation.
			</p>
			<p>
				The following code snippet sets the current time, creates a statement and prints the next scheduled time which is 1 minute later then the current time:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// set start time to the current time.
runtime.getEventService().advanceTime(System.currentTimeMillis());

// deploy a module
// sample EPL: select current_timestamp() as ct from pattern[every timer:interval(1 minute)]
runtime.getDeploymentService().deploy(compiled); // compiled is a module you compiled earlier

// print next schedule time
System.out.println("Next schedule at " + new Date(runtime.getEventService().getNextScheduledTime()));</pre>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="tip">
				<h2>Tip</h2>
				<p>
					If you find that your application requires control over time only for specific deployments and not for other deployments, please read up on <a class="xref" href="apiruntime.html#apiruntime-stages" title="16.21. Stages">Section 16.21, “Stages”</a>.
				</p>
			</div>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="warning">
				<h2>Warning</h2>
				<p>
					You may not use <code class="literal">advanceTime</code> or <code class="literal">advanceTimeSpan</code> to control time when using internal timer since the internal timer tracks system time
					and must be the only source of time.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-time-timespan"></a>16.9.1. Controlling Time Using Time Span Events</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">advanceTime</code> method allows your application to advance runtime time to a given point in time.
					In addition, the <code class="literal">getNextScheduledTime</code> method in <code class="literal">EPEventService</code> returns the next scheduled time according to started statements.
					You would typically use <code class="literal">advanceTime</code> to advance time at a relatively high resolution i.e. milliseconds or microseconds.
				</p>
				<p>
					To advance time for a span of time without individual calls to <code class="literal">advanceTime</code> the API provides the method <code class="literal">advanceTimeSpan</code>. The <code class="literal">advanceTimeSpan</code> method can accept a resolution parameter.
				</p>
				<p>
					If your application provides the target end time of a time span to the <code class="literal">advanceTimeSpan</code> method and does not provide a resolution, the runtime advances time up to the target time by stepping through all relevant times according to started statements.
				</p>
				<p>
					If your application provides the target end time of a time span and in addition a <code class="literal">long</code>-typed resolution to the <code class="literal">advanceTimeSpan</code> method the runtime advances time up to the target time by incrementing time according to the resolution (regardless of next scheduled time according to started statements).
				</p>
				<p>
					Consider the following example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Set start time to Jan.1, 2010, 00:00 am for this example
SimpleDateFormat format = new SimpleDateFormat("yyyy MM dd HH:mm:ss SSS");
Date startTime = format.parse("2010 01 01 00:00:00 000");
runtime.getEventService().advanceTime(startTime.getTime());

// deploy a module
// sample EPL: select current_timestamp() as ct from pattern[every timer:interval(1 minute)]
runtime.getDeploymentService().deploy(compiled); // compiled is a module you compiled earlier
stmt.addListener(...);	// add a listener

// Advance time to 10 minutes after start time
runtime.getEventService().advanceTimeSpan(startTime.getTime() + 10*60*1000));</pre>
				<p>
					The above example advances time to 10 minutes after the start time using the <code class="literal">advanceTimeSpan</code> method. As the example does not pass a resolution, the runtime advances time according to statement schedules. Upon calling the <code class="literal">advanceTimeSpan</code> method the listener sees 10 invocations for minute 1 to minute 10.
				</p>
				<p>
					To advance time according to a given resolution, you may provide the resolution as shown below:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Advance time to 10 minutes after start time at 100 msec resolution
runtime.getEventService().advanceTimeSpan(startTime.getTime() + 10*60*1000, 100);</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-time-resolution"></a>16.9.2. Time Resolution and Time Unit</h3>
						</div>
					</div>
				</div><a id="d0e45166" class="indexterm"></a>
				<p>
					Time can have a resolution of either milliseconds or microseconds.
				</p>
				<p>
					The default time resolution is milliseconds. To configure the runtime for microsecond resolution, please see <a class="xref" href="configuration.html#configuration-common-timesource-timeunit" title="17.4.14.1. Time Unit">Section 17.4.14.1, “Time Unit”</a>.
				</p>
				<div class="table"><a id="d0e45177"></a>
					<p class="title"><b>Table 16.7. Time Resolution</b></p>
					<div class="table-contents">
						<table summary="Time Resolution" border="1">
							<colgroup>
								<col>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th> </th>
									<th>Millisecond</th>
									<th>Microsecond</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>Smallest unit for advancing time</td>
									<td>1 millisecond</td>
									<td>1 microsecond</td>
								</tr>
								<tr>
									<td>Equivalent <code class="literal">java.util.concurrent.TimeUnit</code></td>
									<td>TimeUnit.MILLISECONDS</td>
									<td>TimeUnit.MICROSECONDS</td>
								</tr>
								<tr>
									<td>Default?</td>
									<td>Default</td>
									<td>Requires configuration change, see <a class="xref" href="configuration.html#configuration-common-timesource-timeunit" title="17.4.14.1. Time Unit">Section 17.4.14.1, “Time Unit”</a></td>
								</tr>
								<tr>
									<td>Long-type runtime time represents</td>
									<td>Milliseconds since Epoch</td>
									<td>Microseconds since Epoch</td>
								</tr>
								<tr>
									<td>Example: the date Tue, 01 Jan 1980 00:00:00 GMT</td>
									<td>315532800000</td>
									<td>315532800000000</td>
								</tr>
								<tr>
									<td>Support for Internal System Time</td>
									<td>Yes</td>
									<td>No, requires external time (aka. event time) via <code class="literal">advanceTimeSpan</code> or <code class="literal">advanceTime</code></td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
				<p>
					A few notes on usage of microsecond time unit for time resolution:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							<p>
								The runtime automatically computes time periods into microseconds. For example <code class="literal">1 minute 2 seconds</code> is <code class="literal">62000000</code> microseconds (<code class="literal">62 * 1000000</code>).
							</p>
						</li>
						<li>
							<p>
								The runtime automatically computes time-in-second parameters into microseconds. For example <code class="literal">5.02 seconds</code> is <code class="literal">5020000</code> microseconds.
							</p>
						</li>
						<li>
							<p>
								The runtime automatically computes ISO schedules, crontabs and hints related to runtime time into microseconds.
							</p>
						</li>
						<li>
							<p>
								The <code class="literal">CurrentTimeSpanEvent</code> or <code class="literal">CurrentTimeEvent</code> events must provide microsecond values.
							</p>
						</li>
						<li>
							<p>
								Date-time methods with long-type input values assume microsecond values.
							</p>
						</li>
						<li>
							<p>
								Date-time methods or other functions that take millisecond parameters or produce millisecond values still consume/produce millisecond values, such as the date-time method <code class="literal">toMillisec</code>.
							</p>
						</li>
						<li>
							<p>
								The internal timer must be disabled (<code class="literal">setInternalTimerEnabled(false)</code>) and <code class="literal">TimerControlEvent.ClockType.CLOCK_INTERNAL</code> cannot be used.
							</p>
						</li>
					</ul>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-time-internal"></a>16.9.3. Internal Timer Based on JVM System Time</h3>
						</div>
					</div>
				</div>
				<p>
					By default the internal timer is enabled and that tracks VM system time. For many use cases your application may want to use event time or external time instead, as discussed above.
				</p>
				<p>
					The internal timer thread, by default, uses the call <code class="literal">System.currentTimeMillis()</code> to obtain system time. Please see the JIRA issue ESPER-191 Support nano/microsecond resolution for more information on Java system time-call performance, accuracy and drift.
				</p>
				<p>
					The internal timer thread can be configured to use nanosecond time as returned by <code class="literal">System.nanoTime()</code>. If configured for nanosecond time, the runtime computes an offset of the nanosecond ticks to wall clock time upon startup to present back an accurate millisecond wall clock time.
					Please see section <a class="xref" href="configuration.html#configuration-runtime-timesource" title="17.6.6. Runtime Settings Related to Time Source">Section 17.6.6, “Runtime Settings Related to Time Source”</a> to configure the internal timer thread to use <code class="literal">System.nanoTime()</code>.
				</p>
				<p>
					The internal timer is based on <code class="literal">java.util.concurrent.ScheduledThreadPoolExecutor</code> and that generally provides high accuracy VM time
					(<code class="literal">java.util.Timer</code> does not support high accuracy VM time).
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-exception"></a>16.10. Exception Handling</h2>
					</div>
				</div>
			</div>
			<p>
				You may register one or more exception handlers for the runtime to invoke in the case it encounters an exception processing a continuously-executing statement. By default and without exception handlers the runtime cancels execution of the current statement that encountered the exception, logs the exception and continues to the next statement, if any. The configuration is described in <a class="xref" href="configuration.html#configuration-runtime-exceptionhandling" title="17.6.11. Runtime Settings Related to Exception Handling">Section 17.6.11, “Runtime Settings Related to Exception Handling”</a>.
			</p>
			<p>
				If your application registers exception handlers as part of runtime configuration, the runtime invokes the exception handlers in the order they are registered passing relevant exception information such as statement name, expression and the exception itself.
			</p>
			<p>
				Exception handlers receive any statement unchecked exception such as internal exceptions or exceptions thrown by plug-in aggregation functions or plug-in data windows. The runtime does not provide to exception handlers any exceptions thrown by static method invocations for function calls, method invocations in joins, methods on variables and event classes and listeners or subscriber exceptions.
			</p>
			<p>
				An exception handler can itself throw a runtime exception to cancel execution of the current event against any further statements.
			</p>
			<div xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="note">
				<h2>Note</h2>
				<p>
					Exceptions are meant to indicate an actual unexpected problem.
				</p>
				<p>
					We do not recommend explicitly throwing exceptions for the purpose of flow control, preempting execution or other normal situations.
				</p>
				<p>
					The runtime does not guarantee that throwing an exception has no other side effect and the runtime may not roll back changes that are already made to state.
				</p>
			</div>
			<p>
				For fire-and-forget queries the API indicates any exception directly back to the caller without the exception handlers being invoked, as exception handlers apply to statements only. The same applies to any API calls other than <code class="literal">sendEvent</code> and the <code class="literal">EventSender</code> methods.
			</p>
			<p>
				As the configuration section describes, your application registers one or more classes that implement the <code class="literal">ExceptionHandlerFactory</code> interface in the runtime configuration. Upon runtime initialization the runtime obtains a factory instance from the class name that then provides the exception handler instance. The exception handler class must implement the <code class="literal">ExceptionHandler</code> interface.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-condition"></a>16.11. Condition Handling</h2>
					</div>
				</div>
			</div>
			<p>
				You may register one or more condition handlers for the runtime to invoke in the case it encounters certain conditions, as outlined below, when executing a statement. By default and without condition handlers the runtime logs the condition at informational level and continues processing. The configuration is described in <a class="xref" href="configuration.html#configuration-runtime-conditionhandling" title="17.6.12. Runtime Settings Related to Condition Handling">Section 17.6.12, “Runtime Settings Related to Condition Handling”</a>.
			</p>
			<p>
				If your application registers condition handlers as part of runtime configuration, the runtime invokes the condition handlers in the order they are registered passing relevant condition information such as statement name, expression and the condition information itself.
			</p>
			<p>
				Currently the only conditions indicated by this facility are raised by the pattern followed-by operator, see <a class="xref" href="event_patterns.html#pattern-temporal-followed-by-max" title="7.5.8.1. Limiting Sub-Expression Count">Section 7.5.8.1, “Limiting Sub-Expression Count”</a> and see <a class="xref" href="event_patterns.html#pattern-temporal-followed-by-runtime-max" title="7.5.8.2. Limiting Runtime-Wide Sub-Expression Count">Section 7.5.8.2, “Limiting Runtime-Wide Sub-Expression Count”</a>.
			</p>
			<p>
				A condition handler may not itself throw a runtime exception or return any value.
			</p>
			<p>
				As the configuration section describes, your application registers one or more classes that implement the <code class="literal">ConditionHandlerFactory</code> interface in the runtime configuration. Upon runtime initialization the runtime obtains a factory instance from the class name that then provides the condition handler instance. The condition handler class must implement the <code class="literal">ConditionHandler</code> interface.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-instrumentation"></a>16.12. Runtime and Statement Metrics Reporting</h2>
					</div>
				</div>
			</div>
			<p>
				The runtime can report key processing metrics through the JMX platform mbean server by setting a single configuration flag described in <a class="xref" href="configuration.html#configuration-runtime-jmxmetrics" title="17.6.7. Runtime Settings Related to JMX Metrics">Section 17.6.7, “Runtime Settings Related to JMX Metrics”</a>.
				For additional detailed reporting and metrics events, please read on.
			</p>
			<p>
				Metrics reporting is a feature that allows an application to receive ongoing reports about key runtime-level and statement-level metrics. Examples are the number of incoming events, the CPU time and wall time taken by statement executions or the number of output events per statement.
			</p>
			<p>
				Metrics reporting is, by default, disabled. To enable reporting, please follow the steps as outlined in <a class="xref" href="configuration.html#configuration-runtime-metricsreporting" title="17.6.8. Runtime Settings Related to Metrics Reporting">Section 17.6.8, “Runtime Settings Related to Metrics Reporting”</a>. Metrics reporting must be enabled at runtime initialization time. The <code class="literal">EPMetricsService</code> interface, available from the runtime API, provides current metrics and provides control over reporting intervals.
			</p>
			<p>
				Your application can receive metrics at configurable intervals via statement. A metric datapoint is simply a well-defined event. The events are <code class="literal">RuntimeMetric</code> and <code class="literal">StatementMetric</code> and the Java class representing the events can be found in the client API in package <code class="literal">com.espertech.esper.common.client.metric</code>.
			</p>
			<p>
				Since metric events are processed by the runtime the same as application events, your EPL may use any construct on such events. For example, your application may select, filter, aggregate properties, sort or insert into a stream, named window or table all metric events the same as application events.
			</p>
			<p>
				This example statement selects all runtime metric events:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from com.espertech.esper.common.client.metric.RuntimeMetric</pre>
			<p>
				The next statement selects all statement metric events:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from com.espertech.esper.common.client.metric.StatementMetric</pre>
			<p>
				The next statement selects all metric events:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">select * from com.espertech.esper.common.client.metric.MetricEvent</pre>
			<p>
				Make sure to have metrics reporting enabled since only then do listeners or subscribers to a statement such as above receive metric events.
			</p>
			<p>
				The runtime provides metric events after the configured interval of time has passed. By default, only started statements that have activity within an interval (in the form of event or timer processing) are reported upon.
			</p>
			<p>
				The default configuration performs the publishing of metric events in an Esper daemon thread under the control of the runtime instance. Metrics reporting honors externally-supplied time, if using external timer events.
			</p>
			<p>
				Via runtime configuration options provided by <code class="literal">EPMetricsService</code>, your application may enable and disable metrics reporting globally, provided that metrics reporting was enabled at initialization time. Your application may also enable and disable metrics reporting for individual statements by statement name.
			</p>
			<p>
				Statement groups is a configuration feature that allows to assigning reporting intervals to statements. Statement groups are described further in the <a class="xref" href="configuration.html#configuration-runtime-metricsreporting" title="17.6.8. Runtime Settings Related to Metrics Reporting">Section 17.6.8, “Runtime Settings Related to Metrics Reporting”</a> section. Statement groups cannot be added or removed at runtime.
			</p>
			<p>
				The following limitations apply:
			</p>
			<div class="itemizedlist">
				<ul compact="compact">
					<li>
						<p>
							If your Java VM version does not report current thread CPU time (most JVM do), then CPU time is reported as zero (use <code class="literal"> ManagementFactory.getThreadMXBean().isCurrentThreadCpuTimeSupported()</code> to determine if your JVM supports this feature).
						</p>
						<p>
							Note: In some JVM the accuracy of CPU time returned is very low (in the order of 10 milliseconds off) which can impact the usefulness of CPU metrics returned.
							Consider measuring CPU time in your application thread after sending a number of events in the same thread, external to the runtime as an alternative.
						</p>
					</li>
					<li>
						<p>
							Your Java VM may not provide high resolution time via <code class="literal">System.nanoTime</code>. In such case wall time may be inaccurate and inprecise.
						</p>
					</li>
					<li>
						<p>
							CPU time and wall time have nanosecond precision but not necessarily nanosecond accuracy, please check with your Java VM provider.
						</p>
					</li>
					<li>
						<p>
							There is a performance cost to collecting and reporting metrics.
						</p>
					</li>
					<li>
						<p>
							Not all statements may report metrics: The runtime performs certain runtime optimizations sharing resources between similar statements, thereby not reporting on certain statements.
						</p>
					</li>
				</ul>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-instrumentation-runtimemetrics"></a>16.12.1. Runtime Metrics</h3>
						</div>
					</div>
				</div>
				<p>
					Runtime metrics are properties of <code class="literal">RuntimeMetric</code> events:
				</p>
				<div class="table"><a id="api-instrumentation-events-runtime"></a>
					<p class="title"><b>Table 16.8. RuntimeMetric Properties</b></p>
					<div class="table-contents">
						<table summary="RuntimeMetric Properties" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Name</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>runtimeURI</td>
									<td>The URI of the runtime.</td>
								</tr>
								<tr>
									<td>timestamp</td>
									<td>The current runtime time.</td>
								</tr>
								<tr>
									<td>inputCount</td>
									<td>Cumulative number of input events since runtime initialization time. Input events are defined as events send in via application threads as well as <code class="literal">insert into</code> events.</td>
								</tr>
								<tr>
									<td>inputCountDelta</td>
									<td>Number of input events since last reporting period.</td>
								</tr>
								<tr>
									<td>scheduleDepth</td>
									<td>Number of outstanding schedules.</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-instrumentation-statementmetrics"></a>16.12.2. Statement Metrics</h3>
						</div>
					</div>
				</div>
				<p>
					Statement metrics are properties of <code class="literal">StatementMetric</code>. The properties are:
				</p>
				<div class="table"><a id="api-instrumentation-events-statement"></a>
					<p class="title"><b>Table 16.9. StatementMetric Properties</b></p>
					<div class="table-contents">
						<table summary="StatementMetric Properties" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Name</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td>runtimeURI</td>
									<td>The URI of the runtime.</td>
								</tr>
								<tr>
									<td>timestamp</td>
									<td>The current runtime time.</td>
								</tr>
								<tr>
									<td>statementName</td>
									<td>Statement name.</td>
								</tr>
								<tr>
									<td>cpuTime</td>
									<td>Statement processing CPU time (system and user) in nanoseconds (if available by Java VM, obtained from <code class="literal">ThreadMXBean.getCurrentThreadCpuTime</code>).</td>
								</tr>
								<tr>
									<td>wallTime</td>
									<td>Statement processing wall time in nanoseconds (based on <code class="literal">System.nanoTime</code>).</td>
								</tr>
								<tr>
									<td>numInput</td>
									<td>Number of input events to the statement.</td>
								</tr>
								<tr>
									<td>numOutputIStream</td>
									<td>Number of insert stream rows output to listeners or the subscriber, if any.</td>
								</tr>
								<tr>
									<td>numOutputRStream</td>
									<td>Number of remove stream rows output to listeners or the subscriber, if any.</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
				<p>
					The totals reported are cumulative relative to the last metric report.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-monitoring"></a>16.13. Monitoring and JMX</h2>
					</div>
				</div>
			</div>
			<p>
				Enterprise Edition has a library for measuring and reporting memory use for a runtime.
			</p>
			<p>
				The runtime can report key processing metrics through the JMX platform mbean server by setting a single configuration flag described in <a class="xref" href="configuration.html#configuration-runtime-jmxmetrics" title="17.6.7. Runtime Settings Related to JMX Metrics">Section 17.6.7, “Runtime Settings Related to JMX Metrics”</a>.
			</p>
			<p>
				Runtime and statement-level metrics reporting is described in <a class="xref" href="apiruntime.html#apiruntime-instrumentation" title="16.12. Runtime and Statement Metrics Reporting">Section 16.12, “Runtime and Statement Metrics Reporting”</a>.
			</p>
			<p>
				The easiest way to see thread contentions is by using VisualVM when Esper is under load and looking at the Threads tab.
				In the worst case you will see a lot of red color in VisualVM.
				The red line in VisualVM shows the threads that are either in a monitor region or waiting in an entry set for the monitor.
				The monitor is the mechanism that Java uses to support synchronization.
				When a statement is stateful the runtime manages the state using a monitor (lock) per context partition.
			</p>
			<p>
				A JVM profiler can be handy to see how much CPU is spent in Esper by the <code class="literal">sendEvent</code> method.
			</p>
			<p>
				The <code class="literal">jconsole</code> can provide information on the JVM heap. If memory gets tights the performance can drop significantly.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-output-rendering"></a>16.14. Event Rendering to XML and JSON</h2>
					</div>
				</div>
			</div>
			<p>
				The <code class="literal">EPRenderEventService</code> interface offers methods to render events as XML or JSON. Obtain the service from a runtime by calling <code class="literal">getRenderEventService</code> on <code class="literal">EPRuntime</code>.
			</p>
			<p>
				Your application may use the built-in XML and JSON formatters to render output events into a readable textual format, such as for integration or debugging purposes. This section introduces the utility classes in the client <code class="literal">util</code> package for rendering events to strings. Further API information can be found in the JavaDocs.
			</p>
			<p>
				For repeated rendering of events of the same event type or subtypes, it is recommended to obtain a <code class="literal">JSONEventRenderer</code> or <code class="literal">XMLEventRenderer</code> instance and use the <code class="literal">render</code> method provided by the interface. This allows the renderer implementations to cache event type metadata for fast rendering.
			</p>
			<p>
				This example shows how to obtain a renderer for repeated rendering of events of the same type, assuming that <code class="literal">statement</code> is an instance of <code class="literal">EPStatement</code>:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">JSONEventRenderer jsonRenderer = runtime.getRenderEventService().getJSONRenderer(statement.getEventType());</pre>
			<p>
				Assuming that <code class="literal">event</code> is an instance of <code class="literal">EventBean</code>, this code snippet renders an event into the JSON format:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String jsonEventText = jsonRenderer.render("MyEvent", event);</pre>
			<p>
				The XML renderer works the same:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">XMLEventRenderer xmlRenderer = runtime.getRenderEventService().getXMLRenderer(statement.getEventType());</pre>
			<p>
				...and...
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String xmlEventText = xmlRenderer.render("MyEvent", event);</pre>
			<p>
				If the event type is not known in advance or if your application does not want to obtain a renderer instance per event type for fast rendering, your application can use one of the following methods to render an event to a XML or JSON textual format:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String json = runtime.getRenderEventService().renderJSON(event);
String xml = runtime.getRenderEventService().renderXML(event);</pre>
			<p>
				Use the <code class="literal">JSONRenderingOptions</code> or <code class="literal">XMLRenderingOptions</code> classes to control how events are rendered. To render specific event properties using a custom event property renderer, specify an <code class="literal">EventPropertyRenderer</code> as part of the options
				that renders event property values to strings. Please see the JavaDoc documentation for more information.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-output-rendering-json"></a>16.14.1. JSON Event Rendering Conventions and Options</h3>
						</div>
					</div>
				</div>
				<p>
					The JSON renderer produces JSON text according to the standard documented at <code class="literal">http://www.json.org</code>.
				</p>
				<p>
					The renderer formats simple properties as well as nested properties and indexed properties according to the JSON string encoding, array encoding and nested object encoding requirements.
				</p>
				<p>
					The renderer does render indexed properties, it does not render indexed properties that require an index, i.e. if your event representation is backed by POJO objects and your getter method is <code class="literal">getValue(int index)</code>, the indexed property values are not part of the JSON text. This is because the implementation has no way to determine how many index keys there are. A workaround is to have a method such as <code class="literal">Object[] getValue()</code> instead.
				</p>
				<p>
					The same is true for mapped properties that the renderer also renders. If a property requires a Map key for access, i.e. your getter method is <code class="literal">getValue(String key)</code>, such property values are not part of the result text as there is no way for the implementation to determine the key set.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-output-rendering-xml"></a>16.14.2. XML Event Rendering Conventions and Options</h3>
						</div>
					</div>
				</div>
				<p>
					The XML renderer produces well-formed XML text according to the XML standard.
				</p>
				<p>
					The renderer can be configured to format simple properties as attributes or as elements. Nested properties and indexed properties are always represented as XML sub-elements to the root or parent element.
				</p>
				<p>
					The root element name provided to the XML renderer must be the element name of the root in the XML document and may include namespace instructions.
				</p>
				<p>
					The renderer does render indexed properties, it does not render indexed properties that require an index, i.e. if your event representation is backed by POJO objects and your getter method is <code class="literal">getValue(int index)</code>, the indexed property values are not part of the XML text. This is because the implementation has no way to determine how many index keys there are. A workaround is to have a method such as <code class="literal">Object[] getValue()</code> instead.
				</p>
				<p>
					The same is true for mapped properties that the renderer also renders. If a property requires a Map key for access, i.e. your getter method is <code class="literal">getValue(String key)</code>, such property values are not part of the result text as there is no way for the implementation to determine the key set.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-plugin"></a>16.15. Plug-In Loader</h2>
					</div>
				</div>
			</div><a id="d0e45731" class="indexterm"></a>
			<p>
				A plug-in loader is for general use with input adapters, output adapters or EPL code deployment or any other task that can benefits from being part of an Esper configuration file and that follows runtime lifecycle.
			</p>
			<p>
				A plug-in loader implements the <code class="literal">com.espertech.esper.runtime.client.plugin.PluginLoader</code> interface and can be listed in the configuration.
			</p>
			<p>
				Each configured plug-in loader follows the runtime instance lifecycle: When an runtime instance initializes, it instantiates each <code class="literal">PluginLoader</code> implementation class listed in the configuration. The runtime then invokes the lifecycle
				methods of the <code class="literal">PluginLoader</code> implementation class before and after the runtime is fully initialized and before an runtime instance is destroyed.
			</p>
			<p>
				Declare a plug-in loader in your configuration XML as follows:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">...
  &lt;plugin-loader name="MyLoader" class-name="org.mypackage.MyLoader"&gt;
    &lt;init-arg name="property1" value="val1"/&gt;
  &lt;/plugin-loader&gt;
...</pre>
			<p>
				Alternatively, add the plug-in loader via the configuration API:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">Configuration config = new Configuration();
Properties props = new Properties();
props.put("property1", "value1");
config.getRuntime().addPluginLoader("MyLoader", "org.mypackage.MyLoader", props);</pre>
			<p>
				Implement the <code class="literal">init</code> method of your <code class="literal">PluginLoader</code> implementation to receive
				initialization parameters. The runtime invokes this method before the runtime is fully initialized, therefore your implementation
				should not yet rely on the runtime instance within the method body:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class MyPluginLoader implements PluginLoader {
  public void init(String loaderName, Properties properties, EPRuntime runtime) {
     // save the configuration for later, perform checking
  }
  ...</pre>
			<p>
				The runtime calls the <code class="literal">postInitialize</code> method once the runtime completed initialization
				and to indicate the runtime is ready for traffic.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void postInitialize() {
  // Start the actual interaction with external feeds or the runtime here
}
...</pre>
			<p>
				The runtime calls the <code class="literal">destroy</code> method once the runtime is destroyed or initialized for a second time.
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public void destroy() {
  // Destroy resources allocated as the runtime instance is being destroyed
}</pre>
			<p>
				To access the plug-in at runtime, the <code class="literal">getContext</code> method provides access under the name <code class="literal">plugin-loader/</code><span class="emphasis"><em>name</em></span>:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">runtime.getContext().getEnvironment().get("plugin-loader/MyLoader");</pre>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-contextpartitionselection"></a>16.16. Context Partition Selection</h2>
					</div>
				</div>
			</div>
			<p>
				This chapter discusses how to select context partitions. Contexts are discussed in <a class="xref" href="context.html" title="Chapter 4. Context and Context Partitions">Chapter 4, <i>Context and Context Partitions</i></a> and the reasons for context partition selection are introduced in <a class="xref" href="context.html#context_selection" title="4.10. Operations on Specific Context Partitions">Section 4.10, “Operations on Specific Context Partitions”</a>.
			</p>
			<p>
				The section is only relevant when you declare a context. It applies to all different types of hash, partitioned, category, overlapping or other temporal contexts. The section uses a category context for the purpose of illustration. The API discussed herein is general and handles all different types of contexts including nested contexts.
			</p>
			<p>
				Consider a category context that separates bank transactions into small, medium and large:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// declare category context
create context TxnCategoryContext 
  group by amount &lt; 100 as small, 
  group by amount between 100 and 1000 as medium, 
  group by amount &gt; 1000 as large from BankTxn</pre>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// retain 1 minute of events of each category separately
context TxnCategoryContext select * from BankTxn#time(1 minute)</pre>
			<p>
				In order for your application to iterate one or more specific categories it is necessary to identify which category, i.e. which context partition, to iterate. Similarly for fire-and-forget queries, to execute fire-and-forget queries against one or more specific categories, it is necessary to identify which context partition to execute the fire-and-forget query against.
			</p>
			<p>
				Your application may iterate one or more specific context partitions using either the <code class="literal">iterate</code> or <code class="literal">safeIterate</code> method of <code class="literal">EPStatement</code> by providing an implementation of the <code class="literal">ContextPartitionSelector</code> interface.
			</p>
			<p>
				For example, assume your application must obtain all bank transactions for small amounts. It may use the API to identify the category and iterate the associated context partition:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">ContextPartitionSelectorCategory categorySmall = new ContextPartitionSelectorCategory() {
    public Set&lt;String&gt; getLabels() {
      return Collections.singleton("small");
    }
  };
Iterator&lt;EventBean&gt; it = stmt.iterator(categorySmall);</pre>
			<p>
				Your application may execute fire-and-forget queries against one or more specific context partitions by using the <code class="literal">executeQuery</code> method on <code class="literal">EPRuntime</code> or the <code class="literal">execute</code> method on <code class="literal">EPFireAndForgetPreparedQuery</code> and by providing an implementation of <code class="literal">ContextPartitionSelector</code>.
			</p>
			<p>
				Fire-and-forget queries execute against named windows and tables, therefore below statement creates a named window which the runtime manages separately for small, medium and large transactions according to the context declared earlier:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// Named window per category
context TxnCategoryContext create window BankTxnWindow#time(1 min) as BankTxn</pre>
			<p>
				The following code demonstrates how to fire a fire-and-forget query against the small and the medium category:
			</p>
			<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">ContextPartitionSelectorCategory categorySmallMed = new ContextPartitionSelectorCategory() {
    public Set&lt;String&gt; getLabels() {
      return new HashSet&lt;String&gt;(Arrays.asList("small", "medium"));
    }
  };
runtime.getFireAndForgetService().executeQuery(
   "select count(*) from BankTxnWindow", 
   new ContextPartitionSelector[] {categorySmallMed});</pre>
			<p>
				The following limitations apply:
			</p>
			<div class="itemizedlist">
				<ul>
					<li>
						<p>
							Fire-and-forget queries may not join named windows or tables that declare a context.
						</p>
					</li>
				</ul>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="api-contextpartitionselection-selectors"></a>16.16.1. Selectors</h3>
						</div>
					</div>
				</div>
				<p>
					This section summarizes the selector interfaces that are available for use to identify and interrogate context partitions. Please refer to the JavaDoc documentation for package <code class="literal">com.espertech.esper.common.client.context</code> and classes therein for additional information.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorAll</code> or the <code class="literal">ContextPartitionSelectorAll.INSTANCE</code> object to instruct the runtime to consider all context partitions.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorById</code> if your application knows the context partition ids to query. This selector instructs the runtime to consider only those provided context partitions based on their integer id value. The runtime outputs the context partition id in the built-in property <code class="literal">context.id</code>.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorFiltered</code> to receive and interrogate context partitions. Use the <code class="literal">filter</code> method that receives a <code class="literal">ContextPartitionIdentifier</code> to return a boolean indicator whether to include the context partition or not. The <code class="literal">ContextPartitionIdentifier</code> provides information about each context partition. Your application may not retain <code class="literal">ContextPartitionIdentifier</code> instances between <code class="literal">filter</code> method invocations as the runtime reuses the same instance. This selector is not supported with nested contexts.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorCategory</code> with category contexts.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorSegmented</code> with keyed segmented contexts.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorHash</code> with hash segmented contexts.
				</p>
				<p>
					Use an implementation of <code class="literal">ContextPartitionSelectorNested</code> in combination with the selectors described above with nested contexts.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-contextpartitionadmin"></a>16.17. Context Partition Administration</h2>
					</div>
				</div>
			</div><a id="d0e45928" class="indexterm"></a>
			<p>
				This chapter briefly discusses the API to manage context partitions. Contexts are discussed in <a class="xref" href="context.html" title="Chapter 4. Context and Context Partitions">Chapter 4, <i>Context and Context Partitions</i></a>.
			</p>
			<p>
				The section is only relevant when you declare a context. It applies to all different types of hash, partitioned, category, overlapping or other temporal contexts.
			</p>
			<p>
				The <code class="literal">EPContextPartitionService</code> interface offers methods to manage context partitions. Obtain the service from a runtime by calling <code class="literal">getContextPartitionService</code> on <code class="literal">EPRuntime</code>.
			</p>
			<p>
				The context partition admin API allows an application to:
			</p>
			<div class="itemizedlist">
				<ul compact="compact">
					<li>
						<p>
							Interrogate the state and identifiers for existing context partitions.
						</p>
					</li>
					<li>
						<p>
							Determine statements associated to a context and context nesting level.
						</p>
					</li>
					<li>
						<p>
							Receive a callback when new contexts get created and destroyed or when context partitions are allocated and de-allocated.
						</p>
					</li>
					<li>
						<p>
							Obtain context properties.
						</p>
					</li>
				</ul>
			</div>
			<p>
				Please see the JavaDoc documentation for more information.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="api-testing"></a>16.18. Test and Assertion Support</h2>
					</div>
				</div>
			</div><a id="d0e45968" class="indexterm"></a><a id="d0e45971" class="indexterm"></a>
			<p>
				Esper offers a listener and an assertions class to facilitate automated testing of EPL rules, for example when using a test framework such as <code class="literal">JUnit</code> or <code class="literal">TestNG</code>.
			</p>
			<p>
				Esper does not require any specific test framework. If your application has the <code class="literal">JUnit</code> test framework in classpath Esper uses <code class="literal">junit.framework.AssertionFailedError</code> to indicate assertion errors, so as to integrate with continuous integration tools.
			</p>
			<p>
				For detailed method-level information, please consult the JavaDoc of the package <code class="literal">com.espertech.esper.common.client.scopetest</code> and <code class="literal">com.espertech.esper.runtime.client.scopetest</code>.
			</p>
			<p>
				The class <code class="literal">com.espertech.esper.common.client.scopetest.EPAssertionUtil</code> provides methods to assert or compare event property values as well as perform various array arthithmatic, sort events and convert events or iterators to arrays.
			</p>
			<p>
				The class <code class="literal">com.espertech.esper.runtime.client.scopetest.SupportUpdateListener</code> provides an <code class="literal">UpdateListener</code> implementation that collects events and returns event data for assertion.
			</p>
			<p>
				The class <code class="literal">com.espertech.esper.runtime.client.scopetest.SupportSubscriber</code> provides a subscriber implementation that collects events and returns event data for assertion. The <code class="literal">SupportSubscriberMRD</code> is a subscriber that accepts events multi-row delivery. The <code class="literal">SupportSubscriber</code> and <code class="literal">SupportSubscriberMRD</code> work similar to <code class="literal">SupportUpdateListener</code> that is introduced in more detail below.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="api-testing-assertion"></a>16.18.1. <code class="literal">EPAssertionUtil</code> Summary</h3>
						</div>
					</div>
				</div>
				<p>
					The below table only summarizes the most relevant assertion methods offered by <code class="literal">EPAssertionUtil</code>. Methods provide multiple footprints that are not listed in detail below. Please consult the JavaDoc for additional method-level information.
				</p>
				<div class="table"><a id="api-testing-assertion-summary"></a>
					<p class="title"><b>Table 16.10. Method Summary for EPAssertionUtil</b></p>
					<div class="table-contents">
						<table summary="Method Summary for EPAssertionUtil" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Name</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td><code class="literal">assertProps</code></td>
									<td>
										<p>Methods that assert that property values of a single <code class="literal">EventBean</code>, POJO or Map matches compared to expected values.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertPropsPerRow</code></td>
									<td>
										<p>Methods that assert that property values of multiple <code class="literal">EventBean</code>, POJOs or Maps match compared to expected values.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertPropsPerRowAnyOrder</code></td>
									<td>
										<p>Same as above, but any row may match. Useful for unordered result sets.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertEqualsExactOrder</code></td>
									<td>
										<p>Methods that compare arrays, allowing <code class="literal">null</code>. as parameters.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertEqualsAnyOrder</code></td>
									<td>
										<p>Same as above, but any row may match. Useful for unordered result sets.</p>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="api-testing-listener"></a>16.18.2. <code class="literal">SupportUpdateListener</code> Summary</h3>
						</div>
					</div>
				</div>
				<p>
					The below table only summarizes the most relevant methods offered by <code class="literal">SupportUpdateListener</code>. Please consult the JavaDoc for additional information.
				</p>
				<div class="table"><a id="api-testing-listener-summary"></a>
					<p class="title"><b>Table 16.11. Method Summary for SupportUpdateListener</b></p>
					<div class="table-contents">
						<table summary="Method Summary for SupportUpdateListener" border="1">
							<colgroup>
								<col>
								<col>
							</colgroup>
							<thead>
								<tr>
									<th>Name</th>
									<th>Description</th>
								</tr>
							</thead>
							<tbody>
								<tr>
									<td><code class="literal">reset</code></td>
									<td>
										<p>Initializes listener clearing current events and resetting the invoked flag.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">getAndClearIsInvoked</code></td>
									<td>
										<p>Returns the "invoked" flag indicating the listener has been invoked, and clears the flag.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">getLastNewData</code></td>
									<td>
										<p>Returns the last events received by the listener.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">getAndResetDataListsFlattened</code></td>
									<td>
										<p>Returns all events received by the listener as a pair.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertOneGetNewAndReset</code></td>
									<td>
										<p>Asserts that exactly one new event was received and no removed events, returns the event and resets the listener.</p>
									</td>
								</tr>
								<tr>
									<td><code class="literal">assertOneGetNew</code></td>
									<td>
										<p>Asserts that exactly one new event was received and returns the event.</p>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</div><br class="table-break">
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="api-testing-usage"></a>16.18.3. Usage Example</h3>
						</div>
					</div>
				</div>
				<p>
					The next code block is a short but complete programming example that asserts that the properties received from output events match expected value.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String epl = "select personName, count(*) as cnt from PersonEvent#length(3) group by personName";
Configuration configuration = new Configuration();
configuration.getCommon().addEventType(PersonEvent.class);
CompilerArguments compilerArguments = new CompilerArguments(configuration);
EPCompiled compiled = EPCompilerProvider.getCompiler().compile(stmt, compilerArguments);

EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime(configuration);
EPStatement stmt = runtime.getDeploymentService().deploy(compiled).getStatements()[0];

SupportUpdateListener listener = new SupportUpdateListener();
stmt.addListener(listener);

runtime.getEventService().sendEventBean(new PersonEvent("Joe"), "PersonEvent");
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), "personName,cnt".split(","),
    new Object[]{"Joe", 1L});</pre>
				<p>
					A few additional examples are shown below:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String[] fields = new String[] {"property"};			
EPAssertionUtil.assertPropsPerRow(listener.getAndResetDataListsFlattened(), fields, 
    new Object[][]{{"E2"}}, new Object[][]{{"E1"}});</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPAssertionUtil.assertPropsPerRow(listener.getAndResetLastNewData(), fields, 
    new Object[][]{{"E1"}, {"E2"}, {"E3"}});</pre>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">assertTrue(listener.getAndClearIsInvoked());</pre>
				<p>
					Please refer to the Esper codebase test sources for more examples using the assertion class and the listener class.
				</p>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-osgi"></a>16.19. OSGi, Class Loader, Class-For-Name</h2>
					</div>
				</div>
			</div><a id="d0e46182" class="indexterm"></a><a id="d0e46187" class="indexterm"></a><a id="d0e46192" class="indexterm"></a>
			<p>
				The configuration object (<code class="literal">Configuration</code>), in respect to classes, holds the fully-qualified class name and does not generally hold <code class="literal">Class</code> references.
				This is by design since the configuration object can be populated from XML.
			</p>
			<p>
				When deploying compiled modules the runtime may use a class loader to find resources.
				Your application has full control over class-for-name and classloader use. OSGi environments can provide a specific class-for-name and class loader.
				Please refer to <a class="xref" href="configuration.html#configuration-transientobjects" title="17.7. Passing Services or Transient Objects">Section 17.7, “Passing Services or Transient Objects”</a>.
			</p>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="devlifecycle-j2ee"></a>16.20. When Deploying with J2EE</h2>
					</div>
				</div>
			</div><a id="d0e46212" class="indexterm"></a><a id="d0e46217" class="indexterm"></a>
			<p>
				A compiler and runtime can well be deployed as part of a J2EE web or enterprise application archive to a web application server.
				When designing for deployment into a J2EE web application server, please consider the items discussed here.
			</p>
			<p>
				We provide a sample servlet context listener in this section that uses the deployment API to deploy and undeploy modules as part of the servlet lifecycle.
			</p>
			<p>
				The distribution provides a message-driven bean (MDB) example that you may find useful.
			</p>
			<p>
				Esper does not have a dependency on any J2EE or Servlet APIs to allow the runtime to run in any environment or container.
			</p>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="devlifecycle-j2ee-considerations"></a>16.20.1. J2EE Deployment Considerations</h3>
						</div>
					</div>
				</div>
				<p>
					As multiple web applications deployed to a J2EE web application server typically have a separate classloader per application, you should consider whether runtime instances need to be shared between applications or can remain separate runtime instances. Consider the <code class="literal">EPRuntimeProvider</code> a Singleton.
					When deploying multiple web applications, your J2EE container classloader may provide a separate instance of the Singleton <code class="literal">EPRuntimeProvider</code> to each web application resulting in multiple independent runtime instances.
				</p>
				<p>
					To share <code class="literal">EPRuntime</code> instances between web applications, one approach is to add the runtime jar files to the system classpath. A second approach can be to have multiple web applications share the same servet context and have your application place the <code class="literal">EPRuntime</code> instance into a servlet context attribute for sharing. Architecturally you may also consider a single archived application (such as an message-driven bean) that all your web applications communicate to via the JMS broker provided by your application server or an external JMS broker.
				</p>
				<p>
					As per J2EE standards there are restrictions in regards to starting new threads in J2EE application code. Esper adheres to these restrictions: It allows to be driven entirely by external events. To remove all Esper threads, set the internal timer off and leave the advanced threading options turned off.
					To provide timer events when the internal timer is turned off, you should check with your J2EE application container for support of the Java system timer or for support of batch or work loading to send timer events to an runtime instance.
				</p>
				<p>
					As per J2EE standards there are restrictions in regards to input and output by J2EE application code. Esper adheres to these restrictions: By itself it does not start socket listeners or performs any file IO.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="devlifecycle-j2ee-servletcontextlistener"></a>16.20.2. Servlet Context Listener</h3>
						</div>
					</div>
				</div>
				<p>
					When deploying a J2EE archive that contains EPL modules files below is sample code to read and deploy EPL modules files packaged with the enterprise or web application archive when the servlet initializes. The sample undeploys EPL modules when the servlet context gets destroyed.
				</p>
				<p>
					A sample <code class="literal">web.xml</code> configuration extract is:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app&gt;
  &lt;listener&gt;
    &lt;listener-class&gt;SampleServletListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  &lt;context-param&gt;
    &lt;param-name&gt;eplmodules&lt;/param-name&gt;
    &lt;param-value&gt;switchmonitor.epl&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;/web-app&gt;</pre>
				<p>
					A sample servet listener that deploys EPL module files packaged into the archive on context initialization and that undeploys when the application server destroys the context is shown here:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">public class SampleServletListener implements ServletContextListener {

  private List&lt;String&gt; deploymentIds = new ArrayList&lt;String&gt;();
  
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {
      String modulesList = servletContextEvent.getServletContext().getInitParameter("eplmodules");
      List&lt;Module&gt; modules = new ArrayList&lt;Module&gt;();
      if (modulesList != null) {
        String[] split = modulesList.split(",");
        for (int i = 0; i &lt; split.length; i++) {
          String resourceName = split[i].trim();
          if (resourceName.length() == 0) {
            continue;
          }
          String realPath = servletContextEvent.getServletContext().getRealPath(resourceName);
  		Module module = EPCompilerProvider.getCompiler().readModule(new File(realPath));
          modules.add(module);
        }
      }
    
      // Determine deployment order
      ModuleOrder order = ModuleOrderUtil.getModuleOrder(modules, null);
  
      // Deploy
      for (Module module : order.getOrdered()) {
       // compile and deploy here (code not included), add deployment id
        deploymentIds.add(deployment.getDeploymentId());
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  
  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();
    for (String deploymentId : deploymentIds) {
       runtime.getDeploymentService().undeploy(deploymentId);
    }
  }
}</pre>
			</div>
		</div>
		<div class="sect1" lang="en-US">
			<div class="titlepage">
				<div>
					<div>
						<h2 class="title"><a id="apiruntime-stages"></a>16.21. Stages</h2>
					</div>
				</div>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-stages-overview"></a>16.21.1. Overview</h3>
						</div>
					</div>
				</div>
				<p>
					An Esper <span class="emphasis"><em>stage</em></span> is its own little container that can host deployments.
				</p>
				<p>
					A stage processes only those events that an application sends into that stage. A stage does not see any events that an application sends into the runtime.
				</p>
				<p>
					A stage has its own stage time. Time in a stage advances only when an application advances time for that stage. A stage advance times independently of runtime time.
				</p>
				<p>
					Each stage is uniquely identified by a stage URI. Within different runtimes there can be stages of the same stage URI. A stage lives within the runtime instance and gets destroyed when the runtime gets destroyed.
					An application can allocate any number of stages. A stage URI can be any non-null string value.
				</p>
				<p>
					These attributes make stages useful for:
				</p>
				<div class="itemizedlist">
					<ul>
						<li>
							<p>
								Suspend and Resume. Suspend deployments so they don't receive events or don't advance time. Resume deployments when they are needed again.
							</p>
						</li>
						<li>
							<p>
								Initialize, Load, or Catch-Up new Deployments to Existing Event and Time History. Stage deployments and replay events and time until deployments have caught up with history, and then unstage deployments to have them receive runtime events and time.
							</p>
						</li>
						<li>
							<p>
								Replay. Replay events and time, receive results, destroy accumulated state, without affecting other deployments and in parallel to other activity.
							</p>
						</li>
					</ul>
				</div>
				<p>
					In other words, a <span class="emphasis"><em>stage</em></span> allows an application to control event visibility and the concept of time as desired on a deployment level: Events sent into a stage are visible only to those deployments that are staged and are not visible to deployments outside of that stage. Within a stage an application can control time independently, start time at a point in time and advance time at the resolution and pace suitable for the deployments added to that stage.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-stages-api"></a>16.21.2. Stage APIs</h3>
						</div>
					</div>
				</div>
				<p>
					The <code class="literal">getStageService</code> method on <code class="literal">EPRuntime</code> returns the service for managing stages:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPStageService stageService = runtime.getStageService();</pre>
				<p>
					To allocate a stage or obtain an already-allocated stage, use <code class="literal">getStage</code> and pass the stage URI. The new stage current time is the runtime current time.
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPStage stage = stageService.getStage("myStage");</pre>
				<p>
					The <code class="literal">EPStage</code> instance represents the stage. The freshly-allocated stage is empty.
				</p>
				<p>
					The <code class="literal">stage</code> method moves deployments from the runtime to the stage (assume <code class="literal">deploymentId</code> is a deployment id of an existing deployment):
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.stage(Collections.singletonList(deploymentId));</pre>
				<p>
					A given deployment is either currently staged or un-staged. The same deployment is never both staged and un-staged.
				</p>
				<p>
					The <code class="literal">unstage</code> method moves deployments from the stage to the runtime:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.unstage(Collections.singletonList(deploymentId));</pre>
				<p>
					To send events to the stage, use <code class="literal">EPStageEventService</code> which extends the <code class="literal">EPEventService</code> interface:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.getEventService().sendEventBean(new Order(...), "Order");</pre>
				<p>
					To advance time for a stage, also use <code class="literal">EPStageEventService</code>:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.getEventService().advanceTime(myTimeInMillis);</pre>
				<p>
					Finally, call <code class="literal">destroy</code> to destroy the stage. Destroy requires that the stage is empty, i.e. does not have any deployments:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.destroy();</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-stage-examplesuspendresume"></a>16.21.3. Stage Example: Suspending and Resuming a Statement</h3>
						</div>
					</div>
				</div>
				<p>
					By staging deployments, the deployments' time and event processing occurs only when the application explicitly sends events to the stage or advances time for that stage.
				</p>
				<p>
					The example code below compiles and deploys EPL that reports order events:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">String module =
    "@public @buseventtype create schema OrderEvent(price double);\n" +
    "@name('All-Order-Events') select * from OrderEvent;\n";
  EPCompiled compiled = EPCompilerProvider.getCompiler().compile(module, null);
  EPRuntime runtime = EPRuntimeProvider.getDefaultRuntime();
  EPDeployment deployment = runtime.getDeploymentService().deploy(compiled);
  deployment.getStatements()[0].addListener(new SupportUpdateListener());</pre>
				<p>
					The <code class="literal">stage</code> method stages the deployment:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">EPStage stage = runtime.getStageService().getStage("myStage");
stage.stage(Collections.singletonList(deployment.getDeploymentId()));</pre>
				<p>
					The staged deployment only receives <code class="literal">OrderEvent</code> events that an application send into the stage. It does not receive <code class="literal">OrderEvent</code> events that an application sends into the runtime (the <code class="literal">EPEventService</code> returned by <code class="literal">getEventService</code> of <code class="literal">EPRuntime</code>). For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// The listener receives the following event
stage.getEventService().sendEventMap(Collections.singletonMap("price", 100d), "OrderEvent");

// The listener DOES NOT receive the following event
runtime.getEventService().sendEventMap(Collections.singletonMap("price", 200d), "OrderEvent");</pre>
				<p>
					The <code class="literal">unstage</code> method un-stages the deployment:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.unstage(Collections.singletonList(deployment.getDeploymentId()));</pre>
				<p>
					The un-staged deployment only receives <code class="literal">OrderEvent</code> events that an application sends into the runtime. It does not receive <code class="literal">OrderEvent</code> events that an application sends into the stage. For example:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">// The listener DOES NOT receive the following event
stage.getEventService().sendEventMap(Collections.singletonMap("price", 100d), "OrderEvent");

// The listener receives the following event
runtime.getEventService().sendEventMap(Collections.singletonMap("price", 200d), "OrderEvent");</pre>
				<p>
					Finally, destroy the stage when it is no longer needed:
				</p>
				<pre xmlns="" xmlns:d="http://docbook.org/ns/docbook" xmlns:rf="java:org.jboss.highlight.XhtmlRendererFactory" class="">stage.destroy();</pre>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-stage-otherconsiderations"></a>16.21.4. Stage Other Considerations</h3>
						</div>
					</div>
				</div>
				<p>
					When staging and unstaging, existing schedules are adjusted for the time difference between stage and runtime, if any.
					For example, assume a pattern <code class="literal">pattern[timer:interval(10 minutes)]</code> deployed at 9:00:00, which would fire at 9:10:00.
					If the time of the target is 8:55:00 or 9:05:00 the pattern still fires at 9:10:00. If the time of the target is after, for example 9:15:00, the pattern fires when time advances again.
				</p>
				<p>
					Staging and un-staging deployments is an inexpensive operation in general.
				</p>
				<p>
					When using advanced threading options, each stage has its own threading i.e. its own thread pool and queues.
				</p>
				<p>
					Each stage has its own metrics reporting, when enabled.
				</p>
				<p>
					Stage use the some configuration values as provided for the runtime.
				</p>
			</div>
			<div class="sect2" lang="en-US">
				<div class="titlepage">
					<div>
						<div>
							<h3 class="title"><a id="apiruntime-stage-limitations"></a>16.21.5. Stage Limitations</h3>
						</div>
					</div>
				</div>
				<p>
					Deployments that have dependencies on other deployments require additional consideration. Such deployments may provide EPL objects to other deployments, and deployments may consume EPL objects from other deployments.
					For example, a deployment may create a named window and another deployment may query the named window.
				</p>
				<p>
					When staging deployments that have dependencies on other deployments, such EPL-object-providing or EPL-object-consuming deployments must also be staged or unstaged in the same operation.
				</p>
			</div>
		</div>
	</div>
	<ul xmlns:d="http://docbook.org/ns/docbook" class="docnav">
		<li class="previous"><a accesskey="p" href="apicompiler.html"><strong>Prev</strong>Chapter 15. Compiler Reference</a></li>
		<li class="up"><a accesskey="u" href="#"><strong>Top of page</strong></a></li>
		<li class="home"><a accesskey="h" href="index.html"><strong>Front page</strong></a></li>
		<li class="next"><a accesskey="n" href="configuration.html"><strong>Next</strong>Chapter 17. Configuration</a></li>
	</ul>
</body>

</html>